I have a parent class that is not managed by Spring which has multiple @Component's inherited from it:
public class Parent {
public void commonMethod(SomeObj obj) {
//...
}
}
@Component
public class ChildA extends Parent {
public MyObj doSomething(/*...*/) {
// Some external call
commonMethod(obj);
}
}
@Component
public class ChildB extends Parent {
public MyObj doSomething(/*...*/) {
// Some external call
commonMethod(obj);
}
}
Now I need to call a Spring managed @Service from the Parent class. Of course, since Parent is not a Spring-managed bean, I was thinking to do something like:
@Service
public class SomeServiceImpl implements SomeService {
public void serviceWork(MyObj obj) {
// Some static method call
}
}
public class Parent {
private SomeService someService;
public Parent(SomeService someService) { this.someService = someService; }
public void commonMethod(MyObj obj) {
someService.serviceWork(obj);
//...
}
}
@Component
public class ChildA extends Parent {
public ChildA(@Autowired SomeService someService) { super(someService); }
public MyObj doSomething(/*...*/) {
// Some external call
commonMethod(obj);
}
}
@Component
public class ChildB extends Parent {
public ChildA(@Autowired SomeService someService) { super(someService); }
public MyObj doSomething(/*...*/) {
// Some external call
commonMethod(obj);
}
}
My question is, is this thread safe? Second, is there a better design for this since now I have to @Autowired SomeService and pass it to Parent's constructor for every child class.
Can I make the Parent class a Spring-managed class? Would that cause any issues since now it becomes a singleton class that's being shared among all the children?