我有以下配置:
<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的情况下会发生这种情况?
答案 0 :(得分:0)
据我所知 - 这是不可能的。我看到两个选择:
proxyMode = ScopedProxyMode.TARGET_CLASS
添加到您的@Scope
注释。@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Bean1 bean1() {
return new Bean1();
}
@Scope
注释以及所有细节,可以创建自定义注释:@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();
}