2013-10-24 107 views
0

我在理解如何使用註釋時遇到了一些問題,特別是對於bean。Spring註釋組件

我有一個組件

@Component 
public class CommonJMSProducer 

而且我想在其他類中使用它,我想我能做到這一點有一個唯一的對象

public class ArjelMessageSenderThread extends Thread { 
    @Inject 
    CommonJMSProducer commonJMSProducer; 

但commonJMSProducer爲空。

在我appContext.xml我有這樣的:

<context:component-scan base-package="com.carnot.amm" /> 

感謝

+0

如何創建ArjelMessageSenderThread'的'實例? – micha

回答

1

你必須春配置爲使用此功能自動裝配:

<context:annotation-config/>

你可以找到的細節基於註釋的配置here

ArjelMessageSenderThread也必須由Spring管理,否則它不會篡改它的成員,因爲它不知道它。

OR

,如果你不能讓一個託管Bean,那麼你可以做這樣的事情:

ApplicationContext ctx = ... 
ArjelMessageSenderThread someBeanNotCreatedBySpring = ... 
ctx.getAutowireCapableBeanFactory().autowireBeanProperties(
    someBeanNotCreatedBySpring, 
    AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT, true); 

OR

爲別人指出你可以使用註解在Spring中沒有使用@Configurable註解創建的對象上使用依賴注入。

+0

'component-scan'包含'annotation-config'。 –

0

這取決於您如何創建ArjelMessageSenderThread的實例。

如果ArjelMessageSenderThread是一個應該在春天創建的bean,您只需添加@Component(並確保該組件被掃描組件掃描)。

但是,由於您擴展Thread,我不認爲這應該是一個標準的Spring bean。如果您使用new自己創建ArjelMessageSenderThread的實例,則應將@Configurable註釋添加到ArjelMessageSenderThread。使用@Configurable依賴性將被注入,即使該實例不是由Spring創建的。請參閱documentation of @Configurable瞭解更多詳情,並確保您啓用了load time weaving

0

我使用XML而不是註釋。這似乎不是一件大事。目前,我只是有這個更多的XML

<bean id="jmsFactoryCoffre" class="org.apache.activemq.pool.PooledConnectionFactory" 
    destroy-method="stop"> 
    <constructor-arg name="brokerURL" type="java.lang.String" 
     value="${brokerURL-coffre}" /> 
</bean> 

<bean id="jmsTemplateCoffre" class="org.springframework.jms.core.JmsTemplate"> 
    <property name="connectionFactory"> 
     <ref local="jmsFactoryCoffre" /> 
    </property> 
</bean> 

<bean id="commonJMSProducer" 
    class="com.carnot.CommonJMSProducer"> 
    <property name="jmsTemplate" ref="jmsTemplateCoffre" /> 
</bean> 

而另一個類來獲取豆

@Component 
public class ApplicationContextUtils implements ApplicationContextAware { 

還是要謝謝你