Reputation: 41
I have a factory class that should return me an instance of classA
or classB
. These classes implement interface XYZ
:
interface xyz;
getInstance()
@service
classA implements xyz{
public void checkStatus(){
}
}
@service classB implements xyz{
public void checkStatus(){
}
}
Factory class:
@component
class ABCFactory{
@Autowire classA A;
public static getInstance(str a){
return classA;
}
}
Client code:
Class A a = ABCFactory.getInstance("A");
a.checkStatus();
I get null pointer exception -- probably a
is returned as null?
What is the best approach to implement the factory pattern with spring annotation and autowired bean?
Upvotes: 1
Views: 1923
Reputation: 340743
static
is the root of all evil. How did you managed to access classA
here?
@Component
class ABCFactory{
@Autowire classA A;
public static getInstance(str a){
return classA;
}
}
A
field is not static while getInstance()
method is - your code won't compile.
Furthermore, dependency injection works on instances, not on static
classes. Thus you should get rid of static
:
@Component
class ABCFactory {
@Autowire classA A;
public xyz getInstance(str a){
return A;
}
}
and inject ABCFactory
where you need it (e.g. in other services or controllers):
@Autowired
private ABCFactory factory;
BTW your design looks supicious in Spring environment, what do you want to achieve?
Upvotes: 0
Reputation: 24350
It's difficult to say with any certainty why your auto-wiring isn't taking place without seeing your Spring config. My first guess is that you don't have component scanning switched on:
<context:component-scan base-package="org.example"/>
Adding something like that to your spring config file (with the correct package) will tell Spring to scan the package structure for fields that need to be auto-wired, and services that can be used for auto-wiring.
Upvotes: 1