不为@ Bean定义的bean创建Scoped代理(Spring 4.0.5)

时间:2014-11-30 20:50:14

标签: spring

我有以下配置:

<context:component-scan base-package="my.spring.mvc" scoped-proxy="targetClass"/>

我原本期望我的所有scoped bean都会被包装,但它不会影响我@Configuration课程中通过@Bean创建的那些bean。更具体一点:

@Component
@Scope("request")
public class Bean1 {}

工作正常,但是:

// <- no annotations here
public class Bean1

+

@Configuration
public class BeansProducer {
    @Bean
    @Scope(value="request")
    public Bean1 bean1() {
        return new Bean1();
    }
}

不会注入scoped bean(我得到Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean

是否可以根据component-scan的设置确定@ Bean-bean的范围,因为在常规@Component s的情况下会发生这种情况?

1 个答案:

答案 0 :(得分:0)

据我所知 - 这是不可能的。我看到两个选择:

  1. 注释将proxyMode = ScopedProxyMode.TARGET_CLASS添加到您的@Scope注释。
  2. @Bean
    @Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public Bean1 bean1() {
        return new Bean1();
    }
    
    1. 如果您不想一直重复@Scope注释以及所有细节,可以创建自定义注释:
    2. @Target({ElementType.TYPE, ElementType.METHOD})
      @Retention(RetentionPolicy.RUNTIME)
      @Documented
      @Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
      @interface RequestScoped {
      
      }
      

      并注释你的bean:

      @Bean
      @RequestScoped
      public Bean1 bean1() {
          return new Bean1();
      }