Reputation: 13510
I need to wire external lib class to my bean,in order to use it as singleton.
.xml config:
<bean id="myBean" class="com.my.MyBean">
<property name="someLib" value="com.ExternalBean" />
</bean>
java bean:
@Service
public class MyBean {
@Autowired
private ExternalBean externalBean;
public void setExternalBean(ExternalBean externalBean) {
this.externalBean = externalBean;
}
Further I use wired variable externalBean
in public method ,in order not to instantiate it in every method call.
Problem is it null
.
Do I wire bean correctly?What is mistake.
Upvotes: 2
Views: 6276
Reputation: 18639
I think that the better ide ais to use context path scan:
<context:component-scan base-package="some.external.package">
</context:component-scan>
Make sure that all these classes are within the package. Then mark both classes with one of the Annotations (@Repository, @Service, @Component
).
One of the benefits, no setter required.
P.S: If you re using scan base you don't need to declare class as bean, annotations are enough
Upvotes: 1
Reputation: 120791
loodakrawa is right. A second thing that can cause a problem is, that you have a xml bean declaration for myBean
and additional annotated the bean with @Service
. I guess this will cause trouble as soon as use enable component scan.
Upvotes: 1
Reputation: 1574
You have to define the external class as a bean in order to make @Autowired work.
<bean id="externalBean" class="some.external.package.ExternalBean">
</bean>
<bean id="myBean" class="com.my.MyBean">
</bean>
Also, if you use @Autowired you don't need the setter for it.
Upvotes: 5