@Configuration
注解的定义:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
@AliasFor(annotation = Component.class )
String value() default "";
}
在@Component类中使用方法或字段时不会使用CGLIB增强(及不使用代理类:调用任何方法,使用任何变量,拿到的是原始对象,后面会有例子解释)。
而在@Configuration类中使用方法或字段时则使用CGLIB创造协作对象(及使用代理:拿到的是代理对象);当调用@Bean注解的方法时它不是普通的Java语义,而是从容器中拿到由Spring生命周期管理、被Spring代理甚至依赖于其他Bean的对象引用。
在@Component中调用@Bean注解的方法和字段则是普通的Java语义,不经过CGLIB处理。
@Configuration //和使用@Component 做对比
public static class Config {
/*
使用@Component注解需要加这个,才能保证是一个实例
@Autowired
private SimpleBean simpleBean;
*/
@Bean
public SimpleBean simpleBean() {
return new SimpleBean();
}
@Bean
public SimpleBeanConsumer simpleBeanConsumer() {
return new SimpleBeanConsumer(simpleBean());
}
}
@Component
注解并没有通过 cglib 来代理@Bean方法的调用
@Configuration 配置类 加载过程参考:https://www.jb51.net/article/153430.htm
/*
@Configuation等价于<Beans></Beans>
@Bean等价于<Bean></Bean>
*/
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
用于指定 Spring 在初始化容器时要扫描的包,用注解标识的类会被 Spring 自动扫描并且装入 Bean 容器中,作用和在 Spring 的 xml 配置文件中的:<context:component-scan base-package="com..."/>
是一样的
Spring配置类的相关注解@Configuration@Component@Bean@ComponentScan
原文:https://www.cnblogs.com/mewcoder/p/12595590.html