资讯专栏INFORMATION COLUMN

关于Spring Boot你不得不知道的事--Spring Boot的基本操作

fancyLuo / 3438人阅读

摘要:版本和编码方式依赖管理这样比如使用的时候就不需要指定版本号使用自己的项目这时候将依赖管理的问题放到中。

1 Pom文件
1.1 spring-boot-starter-parent
表示当前pom文件从spring-boot-starter-parent继承下来,在spring-boot-starter-parent中提供了很多默认配置,可以简化我们的开发。

org.springframework.boot
spring-boot-starter-parent
2.1.4.RELEASE
 


Java版本和编码方式

UTF-8
1.8
@
${java.version}
UTF-8
${java.version}


依赖管理spring-boot-dependencies

5.15.9
2.7.7
1.9.73
2.6.4
...


这样比如使用starter-web的时候就不需要指定版本号

org.springframework.boot
spring-boot-starter-web
2.1.4.RELEASE


使用自己的parent项目
这时候将依赖管理的问题放到dependencyManagement中。

官网说明文档见:13.2.2 Using Spring Boot without the Parent POM


  
     org.springframework.boot
     spring-boot-dependencies
     2.1.4.RELEASE
     pom
     import
  



1.2 打包管理
使用mvn package打包的plugin。


  
     org.springframework.boot
     spring-boot-maven-plugin
  



1.3 Starters
官网见:13.5 Starters

Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop shop for all the Spring and related technologies that you need without having to hunt through sample code and copy-paste loads of dependency descriptors. For example, if you want to get started using Spring and JPA for database access, include the spring-boot-starter-data-jpa dependency in your project.
官方starter命名
spring-boot-starter-*

自定义starter命名
thirdpartyproject-spring-boot-starter

spring-boot-web-starter
查看其diagram,可以排除某个依赖


org.springframework.boot
spring-boot-starter-web

  
     org.springframework.boot
     spring-boot-starter-tomcat
  



2 XXXApplication
2.1 @SpringBootApplication
官网见:18. Using the @SpringBootApplication Annotation

等同于@EnableAutoConfiguration,@ComponentScan和@Configuration

2.2 SpringApplication.run
官网见:23. SpringApplication

3 配置文件
3.1 初步感受
server.port=9090
3.2 yml文件
application.yml

3.3 给属性注入值
实体类Person和IDCard
public class Person {

private String name;
private int age;
private Date birthday;
private String[] hobbies;
private IDCard idCard;
...

}
public class IDCard {

private int id;
private String number;

}
yml注入写法
person:

name: Jack
age: 17
birthday: 1997/06/01
hobbies: [code,sing,share]
idCard: 
    id: 1
    number: 111

Person类增加注解
@Component
@ConfigurationProperties(prefix="person")
测试
@Autowired
private Person person;
如果Person类上报错,在Pom文件中加入如下依赖

org.springframework.boot
spring-boot-configuration-processor


4 处理动静态资源
4.1 动态资源
官网见:90.2 Reload Templates without Restarting the Container

templates
resources目录下有一个templates文件夹,可以将动态资源放到其中

引入thymeleaf

org.springframework.boot
spring-boot-starter-thymeleaf


templates下新建test.html文件




controller中return test
@Controller
@RequestMapping("/gupao")
public class GupaoController {

@RequestMapping("/hello")
public String hello(Model model){
    String str="hello spring boot";
    //想要动态的显示在网页当中
    model.addAttribute("str",str);
    //接下来的页面是能够动态显示传过来的数据
    return "test";
}

}
4.2 静态资源
static文件夹
在resources目录下有一个static文件夹,可以将静态资源放到其中,浏览器可以直接访问。

静态资源其他存放文件夹
"classpath:/META-INF/resources/"
"classpath:/resources/"
"classpath:/static/"
"classpath:/public/"
WebMvcAutoConfiguration源码分析
WebMvcAutoConfiguration--->WebMvcAutoConfigurationAdapter.addResourceHandlers(xxx)--->

this.resourceProperties.getStaticLocations()
return this.staticLocations;
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {

  "classpath:/META-INF/resources/", "classpath:/resources/",
  "classpath:/static/", "classpath:/public/" };

自定义静态资源文件夹
观察

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {
配置application.properties

spring.resources.static-locations=classpath:/gupao/
5 整合MyBatis
5.1 需求
通过Spring Boot Web项目api接口的方式,整合MyBatis实现crud的操作。

5.2 创建Spring Boot Web项目
重温一下web项目创建的过程。

5.3 引入项目中需要的starter依赖

mysql
mysql-connector-java


org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.1


org.springframework.boot
spring-boot-starter-thymeleaf

5.4 创建数据库表
db_gupao_springboot--->t_user

5.5 创建domain/User对象
public class User {

private int id;
private String username;
private String password;
private String number;
...

}
5.6 开发dao层
@Repository
@Mapper
public interface UserMapper {

User find(String username);
List list();
int insert(User user);
int delete(int id);
int update(User user);

}
5.7 开发service层
@Service
public class UserService {

@Autowired
public UserMapper userMapper;
public User findByUsername(String username){
    return userMapper.find(username);
}
public List listUser(){
    return userMapper.list();
}
public int insertUser(User user){
    return userMapper.insert(user);
}
public int updateUser(User user){
    return userMapper.update(user);
}
public int delete(int id){
    return userMapper.delete(id);
}

}
5.8 开发controller层
@RestController
@RequestMapping(value="/user",method = {RequestMethod.GET,RequestMethod.POST})
public class UserController {

@Autowired
private UserService userService;
@RequestMapping("/listone")
@ResponseBody
public User listOne(String username){
    return userService.findByUsername(username);
}
@RequestMapping("/listall")
@ResponseBody
public List listAll(){
    return userService.listUser();
}

@RequestMapping(value="/add",method= RequestMethod.POST)
@ResponseBody
public String add(User user){
    int result=userService.insertUser(user);
    if(result>=1) {
        return "添加成功";
    }else{
        return "添加失败";
    }
}
@RequestMapping(value="/update",method= RequestMethod.POST)
@ResponseBody
public String update(User user){
    int result=userService.updateUser(user);
    if(result>=1) {
        return "修改成功";
    }else{
        return "修改失败";
    }
}
@RequestMapping(value="/delete",method= RequestMethod.GET)
@ResponseBody
public String delete(int id){
    int result=userService.delete(id);
    if(result>=1) {
        return "删除成功";
    }else{
        return "删除失败";
    }
}

}
5.9 resources目录下创建mapper文件夹---UserMapper.xml

    "-//mybatis.org//DTD com.example.Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">


    
    
    




  INSERT INTO t_user
  (
  id,username,password,number
  )
  VALUES (
  #{id},
  #{username, jdbcType=VARCHAR},
  #{password, jdbcType=VARCHAR},
  #{number}
  )


  delete from t_user where id=#{id}

update t_user set user.username=#{username},user.password=#{password},user.number=#{number} where user.id=#{id}


5.10 application.properties文件配置

数据源

spring:
datasource:

url: jdbc:mysql://127.0.0.1:3306/boot?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis托管mapper文件

mybatis:
mapper-locations: classpath:mapper/*.xml
5.11 启动项目测试
查询
http://localhost:8888/user/listone?username=Jack

全部查询
http://localhost:8888/user/listall

增加
http://localhost:8888/user/add?id=3&username=AAA&password=111111&number=300

更新
http://localhost:8888/user/update?id=3&username=BBB

删除
http://localhost:8888/user/delete?id=3

6 项目打包
jar包
mvn -Dmaven.test.skip -U clean install

java -jar xxx.jar

war包
com.csdn
springboot-demo2
0.0.1-SNAPSHOT
war
7 Spring Boot in less than 10 minutes
https://www.youtube.com/watch...

BUILD ANYTHING WITH SPRING BOOT

Spring Boot is the starting point for building all Spring-based applications. Spring Boot is designed to get you up and running as quickly as possible, with minimal upfront configuration of Spring.

Get started in seconds using Spring Initializr

Build anything: REST API, WebSocket, web, streaming, tasks, and more

Simplified security

Rich support for SQL and NoSQL

Embedded runtime support: Tomcat, Jetty, and Undertow

Developer productivity tools such as LiveReload and Auto Restart

Curated dependencies that just work

Production-ready features such as tracing, metrics, and health status

Works in your favorite IDE: Spring Tool Suite, IntelliJ IDEA, and NetBeans

7.1 IDEA创建工程
group:com.example

artifact:bootiful

dependencies:Reactive Web,Reactive MongoDB,Lombok,Actuator,Security

7.2 DATA DRIVE
Spring Data integrates seamlessly with SQL and NoSQL persistence stores. Spring Data supports reactive data access,too!

@Component
class DataWriter implements ApplicationRunner {

private final CustomerRepository customerRepository;

DataWriter(CustomerRepository customerRepository) {
    this.customerRepository = customerRepository;
}

@Override
public void run(ApplicationArguments args) throws Exception {
    Flux.just("Jack", "Rechal", "Richard", "Jobs")
            .flatMap(name -> customerRepository.save(new Customer(null, name)))
            .subscribe(System.out::println);
}

}
interface CustomerRepository extends ReactiveMongoRepository {
}
@Document
@NoArgsConstructor
@Data
class Customer {

private String id,name;

public Customer(String id, String name) {
    this.id = id;
    this.name = name;
}

}
7.3 REST
On the web,nobody knows you"re a reactive microservice.

@SpringBootApplication
public class BootifulApplication {

@Bean
RouterFunction routes(CustomerRepository cr){
    return RouterFunctions.route(GET("/customers"),serverRequest -> ok().body(cr.findAll(),Customer.class));
}

public static void main(String[] args) {
    SpringApplication.run(BootifulApplication.class, args);
}

}
7.4 OBSERVABILITY
How"s your app"s health?Who better to articulate that then the application itself?

Spring Boot featurese strong opinions,loosely held.

It"s easy to change any of them with properties or pluggable implementations

management.endpoint.health.show-details=always
management.endpoints.web.exposure.exclude=*
@Bean
HealthIndicator healthIndicator(){
return () -> Health.status("I <3 Production").build();
}
访问:curl http://localhost:8080/actuator/health | jq

7.5 SECURITY
Effortlessly plugin authentication and authorization in a traditional or reactive application with Spring Security

@Bean
MapReactiveUserDetailsService users(){

return new MapReactiveUserDetailsService(User.withDefaultPasswordEncoder().username("user").password("pw").roles("USER").build());

}
访问:curl -vu user:pw http://localhost:8080/customers | jq

7.6 TO PRODUCTION
Let"s provision a MongoDB instance,configure our application"s route and MongoDB binding,and then push our application to production with Cloud Foundry.

命令切换到bootiful根目录下

cf services

定位到my-mongodb文件夹

复制对应文件,修改和观察



文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/77866.html

相关文章

  • 关于Spring Boot得不知道

    摘要:采用一套固化的认知来建立生产环境准备的应用。我们采用一套关于固化平台和第三包依赖库的认知,以至于你可以通过最小的烦恼来启动。大多数的应用程序只需要非常少的配置。 1 Spring Boot官网[2.1.5 CURRENT GA] 1.1 Pivotal Wiki Pivotal Software, Inc. is a software and services company base...

    ygyooo 评论0 收藏0
  • 关于微服务得不知道——Spring Boot注解分析

    摘要:注解分析注解定义注解,用于为代码提供元数据。我们可以将元注解看成一种特殊的修饰符,用来解释说明注解,它是注解的元数据。被修改的注解,结合可以指定该注解存在的声明周期。新增的可重复注解。 Spring Boot 注解分析 1 注解1.1 定义Annotation(注解),用于为Java代码提供元数据。简单理解注解可以看做是一个个标签,用来标记代码。是一种应用于类、方法、参数、变量、构造器...

    nevermind 评论0 收藏0
  • Spring Web

    摘要:认证鉴权与权限控制在微服务架构中的设计与实现一引言本文系认证鉴权与权限控制在微服务架构中的设计与实现系列的第一篇,本系列预计四篇文章讲解微服务下的认证鉴权与权限控制的实现。 java 开源项目收集 平时收藏的 java 项目和工具 某小公司RESTful、共用接口、前后端分离、接口约定的实践 随着互联网高速发展,公司对项目开发周期不断缩短,我们面对各种需求,使用原有对接方式,各端已经很...

    Kosmos 评论0 收藏0
  • Nacos系列:基于Nacos配置中心

    摘要:杀只鸡而已,你拿牛刀来做甚释义小团队小项目选择简单的配置管理方式就好了,要什么配置中心,纯属没事找事。,我就啰嗦到这里吧,下面正式介绍作为配置中心是怎么使用的。 前言 在看正文之前,我想请你回顾一下自己待过的公司都是怎么管理配置的,我想应该会有以下几种方式: 1、硬编码没有什么配置不配置的,直接写在代码里面,比如使用常量类优势:对开发友好,开发清楚地知道代码需要用到什么配置劣势:涉及秘...

    ralap 评论0 收藏0
  • SpringBoot 实战 (一) | 如何使用 IDEA 构建 Spring Boot 工程

    摘要:它使用约定大于配置的理念让你的项目快速运行起来。如何使用构建工程第一步,当然是安装傻瓜式教程,请自行百度。包名,填完和后自动生成,默认即可。确认无误,点完成创建即可。 微信公众号:一个优秀的废人如有问题或建议,请后台留言,我会尽力解决你的问题。 前言 新年立了个 flag,好好运营这个公众号。具体来说,就是每周要写两篇文章在这个号发表。刚立的 flag 可不能这么快打脸。下面送上本周第...

    Ryan_Li 评论0 收藏0

发表评论

0条评论

fancyLuo

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<