温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

@Configuration与@Component作为配置类的区别是什么

发布时间:2021-11-25 21:39:06 来源:亿速云 阅读:125 作者:柒染 栏目:编程语言

本篇文章给大家分享的是有关@Configuration与@Component作为配置类的区别是什么,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

@Configuration注解的类:

/** * @Description 测试用的配置类 * @Author 弟中弟 * @CreateTime 2019/6/18 14:35 */@Configurationpublic 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 */@Componentpublic class MyBeanConfig { @Bean public Country country(){  return new Country(); } @Bean public UserInfo userInfo(){  return new UserInfo(country()); }}

测试:

@RunWith(SpringRunner.class)@SpringBootTestpublic 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@Componentpublic @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默认是单例。

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

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

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

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

以上就是@Configuration与@Component作为配置类的区别是什么,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI