第二章 SpringBoot底层注解

1. @Configuration

  • Full模式与Lite模式

    • 使用示例

      /**
       * 1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
       * 2、配置类本身也是组件
       * 3、proxyBeanMethods:代理bean的方法
       *      Full(proxyBeanMethods = true)【保证每个@Bean方法被调用多少次返回的组件都是单实例的】
       *      Lite(proxyBeanMethods = false)【每个@Bean方法被调用多少次返回的组件都是新创建的】
       *      组件依赖必须使用Full模式默认。其他默认是否Lite模式
       */
      @Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
      public class MyConfig {
      
          /**
           * Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
           * @return
           */
          @Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
          public User user01(){
              User zhangsan = new User("zhangsan", 18);
              //user组件依赖了Pet组件
              zhangsan.setPet(tomcatPet());
              return zhangsan;
          }
      
          @Bean("tom")
          public Pet tomcatPet(){
              return new Pet("tomcat");
          }
      }
      
      @SpringBootConfiguration
      @EnableAutoConfiguration
      @ComponentScan("com.atguigu.boot")
      public class MainApplication {
      
          public static void main(String[] args) {
              //1、返回我们IOC容器
              ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
      
              //2、查看容器里面的组件
              String[] names = run.getBeanDefinitionNames();
              for (String name : names) {
                  System.out.println(name);
              }
      
              //3、从容器中获取组件
      
              Pet tom01 = run.getBean("tom", Pet.class);
      
              Pet tom02 = run.getBean("tom", Pet.class);
      
              System.out.println("组件:"+(tom01 == tom02));
      
      
              //4、com.atguigu.boot.config.MyConfig$$EnhancerBySpringCGLIB$$51f1e1ca@1654a892
              MyConfig bean = run.getBean(MyConfig.class);
              System.out.println(bean);
      
              //如果@Configuration(proxyBeanMethods = true)代理对象调用方法。SpringBoot总会检查这个组件是否在容器中有。
              //保持组件单实例
              User user = bean.user01();
              User user1 = bean.user01();
              System.out.println(user == user1);
      
      
              User user01 = run.getBean("user01", User.class);
              Pet tom = run.getBean("tom", Pet.class);
      
              System.out.println("用户的宠物:"+(user01.getPet() == tom));
          }
      }
      
    • 最佳实战

      • 配置类组件之间无依赖关系用Lite模式加速容器启动过程,减少判断
      • 配置类组件之间无依赖关系用Lite模式加速容器启动过程,减少判断

2. Spring管理bean的方式

2.1 注册bean

  • 注册方式

    注册bean主要有两种方式,一种是xml格式,使用@Component注解,被注解的类需要在@ComponentScan扫描的路径下,另一种是javaConfig格式,使用@Configuration+@Bean注解,相当于在配置类中使用bean。

    @Bean注解在方法上,以方法名作为组件的id,返回类型就是组件类型,返回的值,就是组件在容器中的实例。需要在配置类中使用,即类上需要加上 @Component或者@Configuration注解, 通常加上@Configuration。

  • Component分类

    • @Controller 控制层类,@Service 业务层类,@Repository 持久层类,@Component 无法归类到前3种时就称为组件。
    • Controller、Service、Repository其本质就是Component。它存在的本质只是给开发者看的,对Spring而言它们就都是Component。

2.2 自动装配bean

@Component和@Configuration+@Bean都可以用@Autowired注解来自动装配。

3. @Import

 /*
 * @Import({User.class, DBHelper.class})
 *      给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名
 */

@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
public class MyConfig {
}

4. @Conditional

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

5. 原生配置文件导入

5.1 @ImportResource

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       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">

    <bean id="haha" class="com.atguigu.boot.bean.User">
        <property name="name" value="zhangsan"></property>
        <property name="age" value="18"></property>
    </bean>

    <bean id="hehe" class="com.atguigu.boot.bean.Pet">
        <property name="name" value="tomcat"></property>
    </bean>
</beans>
@ImportResource("classpath:beans.xml")
public class MyConfig {}

======================测试=================
boolean haha = run.containsBean("haha");
boolean hehe = run.containsBean("hehe");
System.out.println("haha:"+haha);//true
System.out.println("hehe:"+hehe);//true

5.2 配置绑定

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

public class getProperties {
     public static void main(String[] args) throws FileNotFoundException, IOException {
         Properties pps = new Properties();
         pps.load(new FileInputStream("a.properties"));
         Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
         while(enum1.hasMoreElements()) {
             String strKey = (String) enum1.nextElement();
             String strValue = pps.getProperty(strKey);
             System.out.println(strKey + "=" + strValue);
             //封装到JavaBean。
         }
     }
 }
  • @ConfigurationProperties

    /**
     * 只有在容器中的组件,才会拥有SpringBoot提供的强大功能
     */
    @Component
    @ConfigurationProperties(prefix = "mycar")
    public class Car {
    
        private String brand;
        private Integer price;
    
        public String getBrand() {
            return brand;
        }
    
        public void setBrand(String brand) {
            this.brand = brand;
        }
    
        public Integer getPrice() {
            return price;
        }
    
        public void setPrice(Integer price) {
            this.price = price;
        }
    
        @Override
        public String toString() {
            return "Car{" +
                    "brand='" + brand + '\'' +
                    ", price=" + price +
                    '}';
        }
    } 
    
  • 配置生效

    • @EnableConfigurationProperties(在configuration类上注解) + @ConfigurationProperties

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

5.3 @Configuration与@ConfigurationProperties区别

@Configuration这个注解的主要作用是把使用该注解的类当做Bean来使用,用于配置Spring容器。 @ConfigurationProperties(prefix="xxxx") 用来获取相同父标签的元素的值。被注解的类需要注入到容器中才能生效,可以通过@Component注解或者@Configuration类中@Bean注解注入。

posted @ 2022-01-06 15:15  hunter-w  阅读(41)  评论(0编辑  收藏  举报