I have serices like below
@Service
public class A {
public B data() {
InterfaceA B = (codition) ? new B1() : new B2();
B.check();
}
}
@Service
public class B1 {
@Autowired
private B1Repo b1repo;//repository
public B1 check() {
b1repo.find();
}
}
When I run service A.data()
process I'm getting that b1repo
as null. The repository is not auto-wiring since I'm using new
keyword. I have checked the below issue related_issue
But It didnt help me solve the issue
Spring Framework creates all components instance itself and fills all required auto-wired properties. This is called as Dependency Injection. When you create a new instance of the service class it is a raw instance without auto-wires.
If you have to get an implementation of service by some condition I recommend to use Spring Profiles
@Service
public class A {
@Autowired
private B1 b1;
@Autowired
private B2 b2;
public B data() {
InterfaceA B = (codition) ? b1 : b2;
B.check();
}
}
@Service
public class B1 {
@Autowired
private B1Repo b1repo;//repository
public B1 check() {
b1repo.find();
}
}
When you are applying the SOLID principle of D - Dependency Inversion Principle in spring boot. This may help you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.