1

JSR-330 Scope 注释的 java doc 声明“使用实例进行一次注入,然后忘记它”,这意味着该实例是作用域原型,而 Singleton 注释旨在创建作为 spring 的默认行为的单例。所以问题是,为什么当我使用 Named 注释而不是 Spring Component 注释时,Spring 不遵循 JSR 准则并将 bean 限定为原型?在我看来,它应该如此。

我想将 spring 依赖项合并到一个模块中,并在其他任何地方使用 JSR-330,所以如果需要,我可以在以后轻松切换。

4

1 回答 1

0

所以这就是我制作我想要的东西的方式:

/**
 * 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 应用程序模块完成处理注解的工作。

它对我很有效,但我很高兴听到任何其他建议。

于 2017-07-07T19:31:16.460 回答