1、SpringBoot特点

1.1、依赖管理

  • 父项目做依赖管理 ```xml 依赖管理 org.springframework.boot spring-boot-starter-parent 2.3.4.RELEASE

他的父项目 org.springframework.boot spring-boot-dependencies 2.3.4.RELEASE

1.无需关注版本号,自动版本仲裁(引入非版本仲裁的jar,要写版本号) 2.查看spring-boot-dependencies里面规定当前依赖的版本 spring-boot-starter-parent ——>spring-boot-dependencies 3.可以修改默认版本号,在当前项目里面重写配置 5.1.43

  1. - 开发导入starter场景启动器
  2. ```xml
  3. 1、见到很多 spring-boot-starter-* : *就某种场景
  4. 2、只要引入starter,这个场景的所有常规需要的依赖我们都自动引入
  5. 3、SpringBoot所有支持的场景
  6. https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-starter
  7. 4、见到的 *-spring-boot-starter: 第三方为我们提供的简化开发的场景启动器。
  8. 5、所有场景启动器最底层的依赖
  9. <dependency>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter</artifactId>
  12. <version>2.3.4.RELEASE</version>
  13. <scope>compile</scope>
  14. </dependency>

1.2、自动配置

  • 自动配好Tomcat

    • 引入Tomcat依赖。
    • 配置Tomcat
      1. <dependency>
      2. <groupId>org.springframework.boot</groupId>
      3. <artifactId>spring-boot-starter-tomcat</artifactId>
      4. <version>2.3.4.RELEASE</version>
      5. <scope>compile</scope>
      6. </dependency>
  • 自动配好SpringMVC

    • 引入SpringMVC全套组件
    • 自动配好SpringMVC常用组件(功能)
  • 自动配好Web常见功能,如:字符编码问题
    • SpringBoot帮我们配置好了所有web开发的常见场景
  • 默认的包结构

    • 主程序所在包及其下面的所有子包里面的组件都会被默认扫描进来
    • 无需以前的包扫描配置
    • 想要改变扫描路径,@SpringBootApplication(scanBasePackages=“com.atguigu”)
      • 或者@ComponentScan 指定扫描路径
        1. @SpringBootApplication
        2. 等同于
        3. @SpringBootConfiguration
        4. @EnableAutoConfiguration
        5. @ComponentScan("com.atguigu.boot")

  • 各种配置拥有默认值

    • 默认配置最终都是映射到某个类上,如:MultipartProperties
    • 配置文件的值最终会绑定每个类上,这个类会在容器中创建对象
  • 按需加载所有自动配置项
    • 非常多的starter
    • 引入了哪些场景这个场景的自动配置才会开启
    • SpringBoot所有的自动配置功能都在 spring-boot-autoconfigure 包里面

  • ……

2、容器功能

2.1、组件添加

1、@Configuration

  • 基本使用
  • Full模式与Lite模式
    • 示例
    • 最佳实战
      • 配置 类组件之间无依赖关系用Lite模式加速容器启动过程,减少判断(proxyBeanMethods = false)
      • 配置类组件之间有依赖关系,方法会被调用得到之前单实例组件,用Full模式(proxyBeanMethods = true)
  1. #############################Configuration使用示例######################################################
  2. /**
  3. * 1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
  4. * 2、配置类本身也是组件
  5. * 3、proxyBeanMethods:代理bean的方法(默认true)
  6. * Full(proxyBeanMethods = true)【保证每个@Bean方法被调用多少次返回的组件都是单实例的】
  7. * Lite(proxyBeanMethods = false)【每个@Bean方法被调用多少次返回的组件都是新创建的】
  8. * 组件依赖必须使用Full模式默认。其他默认使用Lite模式
  9. * Full(proxyBeanMethods = true) MyConfig对象为代理对象
  10. */
  11. @Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
  12. public class MyConfig {
  13. /**
  14. * @return
  15. */
  16. @Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
  17. public User user01(){
  18. User zhangsan = new User("zhangsan", 18);
  19. //user组件依赖了Pet组件
  20. zhangsan.setPet(tomcatPet());
  21. return zhangsan;
  22. }
  23. @Bean("tom")
  24. public Pet tomcatPet(){
  25. return new Pet("tomcat");
  26. }
  27. }
  28. ################################@Configuration测试代码如下########################################
  29. @SpringBootConfiguration
  30. @EnableAutoConfiguration
  31. @ComponentScan("com.atguigu.boot")
  32. public class MainApplication {
  33. public static void main(String[] args) {
  34. //1、返回我们IOC容器
  35. ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
  36. //2、查看容器里面的组件
  37. String[] names = run.getBeanDefinitionNames();
  38. for (String name : names) {
  39. System.out.println(name);
  40. }
  41. //3、从容器中获取指定名称的组件
  42. User user = run.getBean( "user01",User.class);
  43. User user1 = run.getBean("user01", User.class);
  44. MyConfig myConfig = run.getBean( MyConfig.class);
  45. MyConfig myConfig1 = run.getBean( MyConfig.class);
  46. Pet pet = run.getBean( "tom",Pet.class);
  47. System.out.println(user1 == user);//true true
  48. System.out.println(myConfig.user01()==myConfig1.user01());//true false
  49. System.out.println(user==myConfig.user01());//true false
  50. System.out.println(user1.getPet() == pet);//true false
  51. System.out.println(myConfig.user01().getPet()==pet);//true false
  52. System.out.println(user1.getPet()==pet);//true false
  53. //如果@Configuration(proxyBeanMethods = true) 代理对象调用方法。SpringBoot总会检查这个组件是否在容器中有。保持组件单实例
  54. //得到结果:true,true,true,true,true,true
  55. //如果@Configuration(proxyBeanMethods = false)每个@Bean方法被调用多少次返回的组件都是新创建的
  56. //得到结果:true,false,false,false,false,false
  57. }
  58. }

2、@Bean、@Component、@Controller、@Service、@Repository

3、@ComponentScan、@Import

  1. * 4@Import({User.class, DBHelper.class})
  2. * 给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名
  3. * 可以是自己定义的类,也可以引用jar中的类
  4. * 注意:是通过实体类中的无参构造器生成对象的
  5. */
  6. @Import({User.class, DBHelper.class})
  7. @Configuration(proxyBeanMethods = false)
  8. public class MyConfig {
  9. }

@Import 高级用法: https://www.bilibili.com/video/BV1gW411W7wy?p=8

4、@Conditional

条件装配:满足Conditional指定的条件,则进行组件注入
image.png

  1. =====================测试条件装配==========================
  2. @Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
  3. //@ConditionalOnBean(name = "tom")
  4. @ConditionalOnMissingBean(name = "tom")
  5. public class MyConfig {
  6. /**
  7. * Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
  8. * @return
  9. */
  10. @Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
  11. public User user01(){
  12. User zhangsan = new User("zhangsan", 18);
  13. //user组件依赖了Pet组件
  14. zhangsan.setPet(tomcatPet());
  15. return zhangsan;
  16. }
  17. @Bean("tom22")
  18. public Pet tomcatPet(){
  19. return new Pet("tomcat");
  20. }
  21. }
  22. public static void main(String[] args) {
  23. //1、返回我们IOC容器
  24. ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
  25. //2、查看容器里面的组件
  26. String[] names = run.getBeanDefinitionNames();
  27. for (String name : names) {
  28. System.out.println(name);
  29. }
  30. boolean tom = run.containsBean("tom");
  31. System.out.println("容器中Tom组件:"+tom);
  32. boolean user01 = run.containsBean("user01");
  33. System.out.println("容器中user01组件:"+user01);
  34. boolean tom22 = run.containsBean("tom22");
  35. System.out.println("容器中tom22组件:"+tom22);
  36. }

2.2、原生配置文件引入

1、@ImportResource

  1. ======================beans.xml=========================
  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
  7. <bean id="haha" class="com.atguigu.boot.bean.User">
  8. <property name="name" value="zhangsan"></property>
  9. <property name="age" value="18"></property>
  10. </bean>
  11. <bean id="hehe" class="com.atguigu.boot.bean.Pet">
  12. <property name="name" value="tomcat"></property>
  13. </bean>
  14. </beans>
  1. @ImportResource("classpath:beans.xml")
  2. public class MyConfig {}
  3. ======================测试=================
  4. boolean haha = run.containsBean("haha");
  5. boolean hehe = run.containsBean("hehe");
  6. System.out.println("haha:"+haha);//true
  7. System.out.println("hehe:"+hehe);//true

2.3、配置绑定

如何使用Java读取到properties文件中的内容,并且把它封装到JavaBean中,以供随时使用;

  1. public class getProperties {
  2. public static void main(String[] args) throws FileNotFoundException, IOException {
  3. Properties pps = new Properties();
  4. pps.load(new FileInputStream("a.properties"));
  5. Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
  6. while(enum1.hasMoreElements()) {
  7. String strKey = (String) enum1.nextElement();
  8. String strValue = pps.getProperty(strKey);
  9. System.out.println(strKey + "=" + strValue);
  10. //封装到JavaBean。
  11. }
  12. }
  13. }

1、@ConfigurationProperties

  1. /**
  2. * 只有在容器中的组件,才会拥有SpringBoot提供的强大功能
  3. */
  4. @Component
  5. @ConfigurationProperties(prefix = "mycar")
  6. public class Car {
  7. private String brand;
  8. private Integer price;
  9. public String getBrand() {
  10. return brand;
  11. }
  12. public void setBrand(String brand) {
  13. this.brand = brand;
  14. }
  15. public Integer getPrice() {
  16. return price;
  17. }
  18. public void setPrice(Integer price) {
  19. this.price = price;
  20. }
  21. @Override
  22. public String toString() {
  23. return "Car{" +
  24. "brand='" + brand + '\'' +
  25. ", price=" + price +
  26. '}';
  27. }
  28. }

2、@EnableConfigurationProperties + @ConfigurationProperties

3、@Component + @ConfigurationProperties

  1. @EnableConfigurationProperties(Car.class)
  2. //1、开启Car配置绑定功能
  3. //2、把这个Car这个组件自动注册到容器中
  4. public class MyConfig {
  5. }

3.4、最佳实践

  • 引入场景依赖
  • 查看自动配置了哪些(选做)
    • 自己分析,引入场景对应的自动配置一般都生效了
    • 配置文件中debug=true开启自动配置报告。Negative(不生效)\Positive(生效)
  • 是否需要修改

    • 参照文档修改配置项
    • 自定义加入或者替换组件
      • @Bean、@Component。。。
    • 自定义器 XXXXXCustomizer
    • …..

      4、开发小技巧

      4.1、Lombok

      简化JavaBean开发

      1. <dependency>
      2. <groupId>org.projectlombok</groupId>
      3. <artifactId>lombok</artifactId>
      4. </dependency>
      5. idea中搜索安装lombok插件

      ```java ===============================简化JavaBean开发=================================== @NoArgsConstructor //@AllArgsConstructor @Data @ToString @EqualsAndHashCode public class User {

      private String name; private Integer age;

      private Pet pet;

      public User(String name,Integer age){ this.name = name; this.age = age; } }

================================简化日志开发=================================== @Slf4j @RestController public class HelloController { @RequestMapping(“/hello”) public String handle01(@RequestParam(“name”) String name){

  1. log.info("请求进来了....");
  2. return "Hello, Spring Boot 2!"+"你好:"+name;
  3. }

}

  1. <a name="PTNhW"></a>
  2. ## 4.2、dev-tools
  3. ```xml
  4. <dependency>
  5. <groupId>org.springframework.boot</groupId>
  6. <artifactId>spring-boot-devtools</artifactId>
  7. <optional>true</optional>
  8. </dependency>

项目或者页面修改以后:Ctrl+F9;

4.3、Spring Initailizr(项目初始化向导)

0、选择我们需要的开发场景

image.png

1、自动依赖引入

image.png

2、自动创建项目结构

image.png

3、自动编写好主配置类

image.png