JSR-330作用域注解的java文档声明“使用实例进行一次注入,然后忘记它”,这意味着该实例是作用域原型,而Singleton注解的目的是创建单例,这是spring的默认行为。因此,问题是,当我使用命名注解而不是Spring组件注解时,Spring为什么不遵循JSR指导方针并将bean的作用域设置为原型?在我看来,这是应该的。
我希望将spring依赖项合并到单个模块中,并在其他任何地方使用JSR-330,这样如果需要,以后可以很容易地切换。
发布于 2017-07-08 03:31:16
这就是我做我想做的事情的方式:
/**
* JSR-330 assumes the default scope is prototype, however Spring IOC defaults to singleton scope.
* This annotation is used to force the JSR-330 standard on the spring application.
*
* This is done by registering this annotation with the spring bean factory post processor.
* <pre>
* <code>
* public class PrototypeBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
*
* public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
* for (String beanName : factory.getBeanDefinitionNames()) {
* if (factory.findAnnotationOnBean(beanName, Prototype.class) != null) {
* BeanDefinition beanDef = factory.getBeanDefinition(beanName);
* beanDef.setScope("prototype");
* }
* }
* }
* }
* </code>
* </pre>
*
* @see javax.inject.Scope @Scope
*/
@Scope
@Documented
@Retention(RUNTIME)
public @interface Prototype {}
我将这个注释放在我的核心jar中,然后让spring-boot app模块来处理这个注释。
它对我来说效果很好,但我很高兴听到任何其他建议。
https://stackoverflow.com/questions/44957871
复制相似问题