1. @Configuration 中所有带 @Bean 注解的方法都会被动态代理,因此调用该方法返回的都是同一个实例
@Configuration 标记的类必须符合下面的要求: 配置类必须以类的形式提供(不能是工厂方法返回的实例),允许通过生成子类在运行时增强(cglib 动态代理)。 配置类不能是 final 类(没法动态代理)。 配置注解通常为了通过 @Bean 注解生成 Spring 容器管理的类, 配置类必须是非本地的(即不能在方法中声明,不能是 private)。
在 @Configuration 注解定义的 bean 方法中可以直接调用方法,不需要 @Autowired 注入后使用。
2. @Component 注解并没有通过 cglib 来代理@Bean 方法的调用.
3.使用@Bean
@Configuration public class MyBeanConfig { @Bean public Country country(){ return new Country(); } @Bean public UserInfo userInfo(){ return new UserInfo(country()); } }
@Component public class MyBeanConfig {
@Autowired private Country country;//否则会是不同的country对象
@Bean public Country country(){ return new Country(); } @Bean public UserInfo userInfo(){ return new UserInfo(country()); } }