当前位置: 移动技术网 > IT编程>开发语言>Java > @Configuration与@Component作为配置类的区别详解

@Configuration与@Component作为配置类的区别详解

2019年07月19日  | 移动技术网IT编程  | 我要评论

@configuration注解的类:

/**
 * @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注解的类:

/**
 * @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());
 }
}

测试:

@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注解的类。

@configuration标记的类必须符合下面的要求:

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

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

配置注解通常为了通过 @bean 注解生成 spring 容器管理的类,

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

任何嵌套配置类都必须声明为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默认是单例。

以上是个人理解,详情源码的分析请看

但是如果我就想用@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实例了

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网