0

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

Fazlan Ahamed
  • 231
  • 4
  • 14
  • You are getting it null because you are creating your own object (using new) and not using the DI object created using @Service class. You have to use Autowire for B1 in A class. – Faizan Burney Nov 24 '20 at 17:11
  • Can you update the above code as per your comment? I dont know how to inject the service in the DI – Fazlan Ahamed Nov 24 '20 at 17:16

2 Answers2

1

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

0
@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.

Fazlan Ahamed
  • 231
  • 4
  • 14