经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
关于Spring Boot你不得不知道的事
来源:cnblogs  作者:昨夜黄花今朝狼  时间:2019/6/21 8:57:20  对本文有异议

1 Pom文件

1.1 spring-boot-starter-parent

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

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.1.4.RELEASE</version>
  5. <relativePath/> <!-- lookup parent from repository -->
  6. </parent>
  • Java版本和编码方式
  1. <properties>
  2. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  3. <java.version>1.8</java.version>
  4. <resource.delimiter>@</resource.delimiter>
  5. <maven.compiler.source>${java.version}</maven.compiler.source>
  6. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  7. <maven.compiler.target>${java.version}</maven.compiler.target>
  8. </properties>
  • 依赖管理spring-boot-dependencies
  1. <properties>
  2. <activemq.version>5.15.9</activemq.version>
  3. <antlr2.version>2.7.7</antlr2.version>
  4. <appengine-sdk.version>1.9.73</appengine-sdk.version>
  5. <artemis.version>2.6.4</artemis.version>
  6. ...
  7. </properties>

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

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. <version>2.1.4.RELEASE</version>
  5. </dependency>
  • 使用自己的parent项目

这时候将依赖管理的问题放到dependencyManagement中。

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

  1. <dependencyManagement>
  2. <dependencies>
  3. <dependency>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-dependencies</artifactId>
  6. <version>2.1.4.RELEASE</version>
  7. <type>pom</type>
  8. <scope>import</scope>
  9. </dependency>
  10. </dependencies>
  11. </dependencyManagement>

1.2 打包管理

使用mvn package打包的plugin。

  1. <build>
  2. <plugins>
  3. <plugin>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-maven-plugin</artifactId>
  6. </plugin>
  7. </plugins>
  8. </build>

1.3 Starters

官网见:13.5 Starters

  1. 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,可以排除某个依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. <exclusions>
  5. <exclusion>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-tomcat</artifactId>
  8. </exclusion>
  9. </exclusions>
  10. </dependency>

2 XXXApplication

2.1 @SpringBootApplication

官网见:18. Using the @SpringBootApplication Annotation

等同于@EnableAutoConfiguration,@ComponentScan和@Configuration

2.2 SpringApplication.run

官网见:23. SpringApplication

3 配置文件

3.1 初步感受

  1. server.port=9090

3.2 yml文件

application.yml

3.3 给属性注入值

  • 实体类Person和IDCard
  1. public class Person {
  2. private String name;
  3. private int age;
  4. private Date birthday;
  5. private String[] hobbies;
  6. private IDCard idCard;
  7. ...
  8. }
  1. public class IDCard {
  2. private int id;
  3. private String number;
  4. }
  • yml注入写法
  1. person:
  2. name: Jack
  3. age: 17
  4. birthday: 1997/06/01
  5. hobbies: [codesingshare]
  6. idCard:
  7. id: 1
  8. number: 111
  • Person类增加注解
  1. @Component
  2. @ConfigurationProperties(prefix="person")
  • 测试
  1. @Autowired
  2. private Person person;

如果Person类上报错,在Pom文件中加入如下依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-configuration-processor</artifactId>
  4. </dependency>

4 处理动静态资源

4.1 动态资源

官网见:90.2 Reload Templates without Restarting the Container

  • templates

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

  • 引入thymeleaf
  1. <!--thymeleaf的jar包-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  5. </dependency>
  • templates下新建test.html文件
  1. <html xmlns:th="http://www.thymeleaf.org">
  2. <head>
  3. </head>
  4. <body>
  5. <span style="color:red; font-size:30pt" th:text="${str}"></span>
  6. </body>
  • controller中return test
  1. @Controller
  2. @RequestMapping("/gupao")
  3. public class GupaoController {
  4. @RequestMapping("/hello")
  5. public String hello(Model model){
  6. String str="hello spring boot";
  7. //想要动态的显示在网页当中
  8. model.addAttribute("str",str);
  9. //接下来的页面是能够动态显示传过来的数据
  10. return "test";
  11. }
  12. }

4.2 静态资源

  • static文件夹

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

  • 静态资源其他存放文件夹
  1. "classpath:/META-INF/resources/"
  2. "classpath:/resources/"
  3. "classpath:/static/"
  4. "classpath:/public/"
  • WebMvcAutoConfiguration源码分析

WebMvcAutoConfiguration--->WebMvcAutoConfigurationAdapter.addResourceHandlers(xxx)--->

  1. this.resourceProperties.getStaticLocations()
  1. return this.staticLocations;
  1. private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
  1. private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
  2. "classpath:/META-INF/resources/", "classpath:/resources/",
  3. "classpath:/static/", "classpath:/public/" };
  • 自定义静态资源文件夹

观察

  1. @ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
  2. public class ResourceProperties {

配置application.properties

  1. 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依赖

  1. <dependency>
  2. <groupId>mysql</groupId>
  3. <artifactId>mysql-connector-java</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.mybatis.spring.boot</groupId>
  7. <artifactId>mybatis-spring-boot-starter</artifactId>
  8. <version>1.3.1</version>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  13. </dependency>

5.4 创建数据库表

db_gupao_springboot--->t_user

5.5 创建domain/User对象

  1. public class User {
  2. private int id;
  3. private String username;
  4. private String password;
  5. private String number;
  6. ...
  7. }

5.6 开发dao层

  1. @Repository
  2. @Mapper
  3. public interface UserMapper {
  4. User find(String username);
  5. List<User> list();
  6. int insert(User user);
  7. int delete(int id);
  8. int update(User user);
  9. }

5.7 开发service层

  1. @Service
  2. public class UserService {
  3. @Autowired
  4. public UserMapper userMapper;
  5. public User findByUsername(String username){
  6. return userMapper.find(username);
  7. }
  8. public List<User> listUser(){
  9. return userMapper.list();
  10. }
  11. public int insertUser(User user){
  12. return userMapper.insert(user);
  13. }
  14. public int updateUser(User user){
  15. return userMapper.update(user);
  16. }
  17. public int delete(int id){
  18. return userMapper.delete(id);
  19. }
  20. }

5.8 开发controller层

  1. @RestController
  2. @RequestMapping(value="/user",method = {RequestMethod.GET,RequestMethod.POST})
  3. public class UserController {
  4. @Autowired
  5. private UserService userService;
  6. @RequestMapping("/listone")
  7. @ResponseBody
  8. public User listOne(String username){
  9. return userService.findByUsername(username);
  10. }
  11. @RequestMapping("/listall")
  12. @ResponseBody
  13. public List<User> listAll(){
  14. return userService.listUser();
  15. }
  16. @RequestMapping(value="/add",method= RequestMethod.POST)
  17. @ResponseBody
  18. public String add(User user){
  19. int result=userService.insertUser(user);
  20. if(result>=1) {
  21. return "添加成功";
  22. }else{
  23. return "添加失败";
  24. }
  25. }
  26. @RequestMapping(value="/update",method= RequestMethod.POST)
  27. @ResponseBody
  28. public String update(User user){
  29. int result=userService.updateUser(user);
  30. if(result>=1) {
  31. return "修改成功";
  32. }else{
  33. return "修改失败";
  34. }
  35. }
  36. @RequestMapping(value="/delete",method= RequestMethod.GET)
  37. @ResponseBody
  38. public String delete(int id){
  39. int result=userService.delete(id);
  40. if(result>=1) {
  41. return "删除成功";
  42. }else{
  43. return "删除失败";
  44. }
  45. }
  46. }

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

  1. <?xml version = "1.0" encoding = "UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC
  3. "-//mybatis.org//DTD com.example.Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.csdn.springbootmybatis.dao.UserMapper">
  6. <resultMap id="result" type="com.gupao.springbootmybatis.domain.User">
  7. <result property="username" column="username"/>
  8. <result property="password" column="password"/>
  9. <result property="number" column="number"/>
  10. </resultMap>
  11. <select id="find" resultMap="result">
  12. SELECT * FROM t_user where username=#{username}
  13. </select>
  14. <select id="list" resultMap="result">
  15. SELECT * FROM t_user
  16. </select>
  17. <insert id="insert" parameterType="com.gupao.springbootmybatis.domain.User"
  18. keyProperty="id" useGeneratedKeys="true">
  19. INSERT INTO t_user
  20. (
  21. id,username,password,number
  22. )
  23. VALUES (
  24. #{id},
  25. #{username, jdbcType=VARCHAR},
  26. #{password, jdbcType=VARCHAR},
  27. #{number}
  28. )
  29. </insert>
  30. <delete id="delete" parameterType="int">
  31. delete from t_user where id=#{id}
  32. </delete>
  33. <update id="update" parameterType="com.gupao.springbootmybatis.domain.User">
  34. update t_user set user.username=#{username},user.password=#{password},user.number=#{number} where user.id=#{id}
  35. </update>
  36. </mapper>

5.10 application.properties文件配置

  1. #数据源
  2. spring:
  3. datasource:
  4. url: jdbc:mysql://127.0.0.1:3306/boot?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
  5. username: root
  6. password: 123456
  7. driver-class-name: com.mysql.cj.jdbc.Driver
  8. #mybatis托管mapper文件
  9. mybatis:
  10. 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包
  1. <groupId>com.csdn</groupId>
  2. <artifactId>springboot-demo2</artifactId>
  3. <version>0.0.1-SNAPSHOT</version>
  4. <packaging>war</packaging>

7 Spring Boot in less than 10 minutes

https://www.youtube.com/watch?v=lhkwLtDIMHI&feature=youtu.be

  1. BUILD ANYTHING WITH SPRING BOOT
  2. 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!

  1. @Component
  2. class DataWriter implements ApplicationRunner {
  3. private final CustomerRepository customerRepository;
  4. DataWriter(CustomerRepository customerRepository) {
  5. this.customerRepository = customerRepository;
  6. }
  7. @Override
  8. public void run(ApplicationArguments args) throws Exception {
  9. Flux.just("Jack", "Rechal", "Richard", "Jobs")
  10. .flatMap(name -> customerRepository.save(new Customer(null, name)))
  11. .subscribe(System.out::println);
  12. }
  13. }
  14. interface CustomerRepository extends ReactiveMongoRepository<Customer, String> {
  15. }
  16. @Document
  17. @NoArgsConstructor
  18. @Data
  19. class Customer {
  20. private String id,name;
  21. public Customer(String id, String name) {
  22. this.id = id;
  23. this.name = name;
  24. }
  25. }

7.3 REST

On the web,nobody knows you're a reactive microservice.

  1. @SpringBootApplication
  2. public class BootifulApplication {
  3. @Bean
  4. RouterFunction<ServerResponse> routes(CustomerRepository cr){
  5. return RouterFunctions.route(GET("/customers"),serverRequest -> ok().body(cr.findAll(),Customer.class));
  6. }
  7. public static void main(String[] args) {
  8. SpringApplication.run(BootifulApplication.class, args);
  9. }
  10. }

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

  1. management.endpoint.health.show-details=always
  2. management.endpoints.web.exposure.exclude=*
  1. @Bean
  2. HealthIndicator healthIndicator(){
  3. return () -> Health.status("I <3 Production").build();
  4. }

访问:curl http://localhost:8080/actuator/health | jq

7.5 SECURITY

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

  1. @Bean
  2. MapReactiveUserDetailsService users(){
  3. return new MapReactiveUserDetailsService(User.withDefaultPasswordEncoder().username("user").password("pw").roles("USER").build());
  4. }

访问: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文件夹

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

大家可以扫描下方二维码关注下我的微信公众号,公众号内没有福利,只会定期生产技术性文章!

原文链接:http://www.cnblogs.com/xueSpring/p/11060708.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号