I'm trying to apply some spring boot code to a legacy project from my work, the problem is that some classes have overloaded constructors and I don't know how to call them using spring boot:
The code looks like this:
@Component
ClassA {
public void doSomething() {
int a;
SomeObjectB b;
ClassB classB = null;
classB = new ClassB(a, ab, b);
}
}
@Service
classB {
@Autowired
private ClassC classC;
classB(int a, SomeObjectA a) {
//Logic with parameters
}
classB(int a, SomeObjectB b) {
//Some logic
classC.someMethod(b)
//More logic
}
classB(int a, SomeObjectC c) {
//Logic with parameters
}
}
@Component
ClassC {
public void someMethod(SomeObjectB b) {
}
}
Within the class ClassA, the classB I'm trying to call is instantiated doing classB = new ClassB(a, ab, b);
therefore the autowired class ClassC is null since is out of the spring context. I have tried to implement a factory method with prototype scope in order to create a new Bean every time the class is called, however is not working as expected.
This is what I've got so far:
@Component
ClassA {
@Autowired
private Function<String, ClassB> myPrototypeFactory;
public void doSomething() {
int a;
SomeObjectB b;
Map myMap = new HashMap<>();
myMap.put("a", a);
myMap.put("b", b);
myPrototypeFactory.apply(myMap);
}
}
@Configuration
ConfigurationClass {
@Bean
public Function<Map<String, Object>, ClassB> myPrototypeFactory() {
return map -> {
return myObjectPrototype((int)map.get("a"), (SomeObjectB)map.get("b"));
};
}
@Bean
@Scope(value = "prototype")
public ClassB myObjectPrototype(int a, SomeObjectB b) {
return new ClassB(a, b);
}
}
So the question is, How do I call an overloaded constructor from ClassB in order to avoid nulls in the @Autowired fields? This is the first time I face this kind of problem.
Any help will be really appreciated.
You can take bean from application context by passing beanName, agruments... If there is multiple constructor then u need to define ClassB prototype
not singleton
..
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
classB {
@Autowired
private ClassC classC;
classB(int a, SomeObjectA a) {
//Logic with parameters
}
classB(int a, SomeObjectB b) {
//Some logic
classC.someMethod(b)
//More logic
}
classB(int a, SomeObjectC c) {
//Logic with parameters
}
}
@Component
ClassA {
@Autowired
private ApplicationContext applicationContext;
public void doSomething() {
int a;
SomeObjectB b;
ClassB classB = null;
classB = (ClassB) applicationContext.getBean("classB", a, ab);
}
}