2017-07-06 23 views
1

JSR-330範圍註釋的java文檔聲明「使用實例進行一次注入,然後忘記它」,這意味着該實例是範圍原型,Singleton註解旨在創建與Spring的默認行爲的單身人士。所以問題是,爲什麼當我使用Named註釋而不是Spring組件註釋時,Spring是否不遵循JSR指導原則並將bean作爲原型範圍?在我看來,它應該。JSR-330 @Scope和Spring不匹配

我想將彈簧依賴關係整合到單個模塊,並在其他地方使用JSR-330,如果需要,我可以稍後輕鬆切換。

+0

由於Spring中的默認值是singleton(如文檔所述),所以它也不會說它們是完全符合JSR-330標準的容器,它們只支持註釋。 –

+0

你想做什麼 - 測試Spring與JSR-330的兼容性?你的代碼有什麼用處? –

+0

該應用程序是一個多模塊gradle項目。這一點的意義在於將DI框架隔離爲單個模塊,並讓其餘模塊使用JSR-330。這將允許我稍後更改DI框架,而無需在每個模塊中進行更改。所以我下面的答案會強制應用程序的spring部分遵循關於bean範圍的JSR規範,並提供每個bean範圍的清晰表示。 – peekay

回答

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 {} 

我把這個註釋在我的核心罐子,然後讓春天啓動的應用程序模塊做處理註釋的工作。

它適用於我,但我很高興聽到任何其他建議。