在@Component类中注册bean是否尊重@Scope?

时间:2018-03-07 00:47:38

标签: spring spring-mvc javabeans

这个website表示在组件类中注册的bean不是代理的cglib,也不是通过spring容器。这是否意味着如果我在组件类(下面的代码段)中注册bean,添加@Scope("请求")将不会产生任何差异,并且将始终创建AnotherBean的新实例什么时候从某个外部类调用testBean.anotherBean()

@Component
public class TestBean {

  @Bean
  @Scope("request")
  public AnotherBean anotherBean() {
    return new AnotherBean();
  }
}

1 个答案:

答案 0 :(得分:2)

不是cglib代理的bean是@Component本身,而不是使用@Bean注释注册的bean。如果您没有显式调用anotherBean方法,那么它将没有区别,因为当调用带有@Bean注释的方法时,代理用于返回bean。参见示例

bean testBeanComponent不是cglib proxied:

@Component
public class TestBeanComponent {

  @Bean
  @Scope("request")
  public AnotherBeanComponent anotherBeanComponent() {
    return new AnotherBeanComponent();
  }
}

bean testBeanConfiguration是cglib proxied:

@Configuration
public class TestBeanConfiguration {

  @Bean
  @Scope("request")
  public AnotherBeanConfiguration anotherBeanConfiguration() {
    return new AnotherBeanConfiguration();
  }
}

意思是:

@Service
public class TestService {

  @Autowired //Inject a normal bean
  private TestBeanComponent testBeanComponent;     

  @Autowired //Inject a proxy
  private TestBeanConfiguration testBeanConfiguration;

  public void test() {
    //Calling anotherBeanComponent always return a new instance of AnotherBeanComponent
    testBeanComponent.anotherBeanComponent()
      .equals(testBeanComponent.anotherBeanComponent()); // is false

    //Calling anotherBeanConfiguration return the bean managed by the container
    testBeanConfiguration.anotherBeanConfiguration()
      .equals(testBeanConfiguration.anotherBeanConfiguration()); // is true
  }
}

但是如果您正在注入bean而不是使用该方法,那么一切都将按预期工作:

@Service
public class TestService2 {

  @Autowired //Inject a proxy with scope request
  private AnotherBeanComponent anotherBeanComponent;     

  @Autowired //Inject a proxy with scope request
  private AnotherBeanConfiguration anotherBeanConfiguration;

}