在@Component和@Configuration

时间:2018-05-04 07:21:50

标签: java spring

@Configuration
public class Config {

   @Bean
   public Student getStudent() {
       return new Student();
   }
}
@Component
public class Config {

   @Bean
   public Student getStudent() {
      return new Student();
   }
}

我想知道使用上述两种方法初始化bean与工厂的区别。

1 个答案:

答案 0 :(得分:1)

两个@Component@Configuration bean方法注册之间存在根本不同。

如果在@Bean内声明@Configuration方法,它将被包装到CGLIB包装器中。进一步调用@Bean方法返回相同的bean实例。

那是:

@Configuration
class A {
  @Bean
  BeanX getBeanX() { ... };

  @Bean
  BeanY getBeanY() {
     return new BeanY(getBeanX()); // You got the same bean instance from getBeanX() method, no matter how many times you call it
                                   // This instance is the container singleton instance
  }
}

如果使用@Component,则每次调用bean方法时,都会创建另一个bean:

@Component
class B {
  @Bean
  BeanX getBeanX() { ... };

  @Bean
  BeanY getBeanY() {
     return new BeanY(getBeanX()); // You got the different bean instance every time you call it
                                   // This getBeanX() instance is different from container singleton instance
  }
}