@Configuration与@Component做为配置类的区别

@Configuration注解的类:java

/** * @Description 测试用的配置类 * @Author 弟中弟 * @CreateTime 2019/6/18 14:35 */
@Configuration
public class MyBeanConfig {
  @Bean
  public Country country(){
    return new Country();
  }
  @Bean
  public UserInfo userInfo(){
    return new UserInfo(country());
  }
}

复制代码

@Component注解的类:spring

/** * @Description 测试用的配置类 * @Author 弟中弟 * @CreateTime 2019/6/18 14:36 */
@Component
public class MyBeanConfig {
  @Bean
  public Country country(){
    return new Country();
  }
  @Bean
  public UserInfo userInfo(){
    return new UserInfo(country());
  }
}
复制代码

测试:bash

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoTest {

    @Autowired
    private Country country;

    @Autowired
    private UserInfo userInfo;

    @Test
    public void myTest() {
        boolean result = userInfo.getCountry() == country;
        System.out.println(result ? "同一个country" : "不一样的country");
    }

}
复制代码

若是是@Configuration打印出来的则是同一个country,@Component则是不一样的country,这是为何呢?测试

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
    @AliasFor(
        annotation = Component.class
    )
    String value() default "";
}
复制代码

你点开@Configuration会发现其实他也是被@Component修饰的,所以context:component-scan/ 或者 @ComponentScan都能处理@Configuration注解的类。spa

@Configuration标记的类必须符合下面的要求:.net

配置类必须以类的形式提供(不能是工厂方法返回的实例),容许经过生成子类在运行时加强(cglib 动态代理)。代理

配置类不能是 final 类(无法动态代理)。code

配置注解一般为了经过 @Bean 注解生成 Spring 容器管理的类,component

配置类必须是非本地的(即不能在方法中声明,不能是 private)。xml

任何嵌套配置类都必须声明为static。

@Bean 方法可能不会反过来建立进一步的配置类(也就是返回的 bean 若是带有

@Configuration,也不会被特殊处理,只会做为普通的 bean)。

可是spring容器在启动时有个专门处理@Configuration的类,会对@Configuration修饰的类cglib动态代理进行加强,这也是@Configuration为何须要符合上面的要求中的部分缘由,那具体会加强什么呢? 这里是我的整理的思路 若是有错请指点

userInfo()中调用了country(),由于是方法那必然country()生成新的new contry(),因此动态代理增长就会对其进行判断若是userInfo中调用的方法还有@Bean修饰,那就会直接调用spring容器中的country实例,再也不调用country(),那必然是一个对象了,由于spring容器中的bean默认是单例。不理解好比xml配置的bean

<bean id="country" class="com.hhh.demo.Country" scope="singleton"/>
复制代码

这里scope默认是单例。

以上是我的理解,详情源码的分析请看https://www.jb51.net/article/153430.htm

可是若是我就想用@Component,那没有@Component的类没有动态代理咋办呢?

/** * @Description 测试用的配置类 * @Author 弟中弟 * @CreateTime 2019/6/18 14:36 */
@Component
public class MyBeanConfig {
  @Autowired
  private Country country;
  @Bean
  public Country country(){
    return new Country();
  }
  @Bean
  public UserInfo userInfo(){
    return new UserInfo(country);
  }
}
复制代码

这样就保证是同一个Country实例了


若是有错请大佬们指点 谢谢 0.0

相关文章
相关标签/搜索