Reputation: 779
I'm having some problems understanding how to use annotations, especially with beans.
I have one component
@Component
public class CommonJMSProducer
And I want to use it in another class and i thought I could do that to have a unique object
public class ArjelMessageSenderThread extends Thread {
@Inject
CommonJMSProducer commonJMSProducer;
but commonJMSProducer is null.
In my appContext.xml I have this :
<context:component-scan base-package="com.carnot.amm" />
Thanks
Upvotes: 0
Views: 197
Reputation: 779
I used XML instead of annotations. This seemed difficult for not a big thing. Currently, I just have this more in the 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>
And another class to get the bean
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
Thanks anyway
Upvotes: 0
Reputation: 30538
You have to configure Spring to use this autowiring feature:
<context:annotation-config/>
You can find the details of annotation-based config here.
ArjelMessageSenderThread
also have to be managed by Spring otherwise it won't tamper with its members since it does not know about it.
OR
if you cannot make it a managed bean then you can do something like this:
ApplicationContext ctx = ...
ArjelMessageSenderThread someBeanNotCreatedBySpring = ...
ctx.getAutowireCapableBeanFactory().autowireBeanProperties(
someBeanNotCreatedBySpring,
AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT, true);
OR
as others pointed out you can use annotations to use dependency injection on objects which are not created by Spring with the @Configurable annotation.
Upvotes: 1
Reputation: 49582
It depends on how you create instances of ArjelMessageSenderThread
.
If ArjelMessageSenderThread
is a bean that should be created by spring you just have to add @Component
(and make sure the package is picked up by the component scan).
However, since you extend Thread
, I don't think this should be a standard Spring bean. If you create instances of ArjelMessageSenderThread
yourself by using new
you should add the @Configurable
annotation to ArjelMessageSenderThread
. With @Configurable
dependencies will be injected even if the instance is not created by Spring. See the documentation of @Configurable for more details and make sure you enabled load time weaving.
Upvotes: 0