2013-10-24 179 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 { 

还是要谢谢你