User3518958
User3518958

Reputation: 716

Injecting a dependency into a library class not managed by spring

I am pretty new to spring or dependency injection. I have an abstract class A in a jar file built already, which is not managed by Spring (This is based on the fact that it does not have any of its dependencies auto-wired, no spring annotations used in the library.).

I have project which needs to use this class and want to inject my implementations of class A's dependency (say, of Type B). This project uses springboot.

How can I inject dependency of type B into A? I tried following : 1. Created a configuration (@Configuration) class and added a method getB() annotated as @Bean which will return object of type B using my implementation of B.

@Bean
public B getB () {
   return new MyB();
}

Upvotes: 2

Views: 2334

Answers (1)

gervais.b
gervais.b

Reputation: 2347

If you want to inject B into A you cannot. Since A is not managed by Spring, the IOC container will never inject anything in a class that he does not know.

The key to your problem is the way you want to get and use the instance of A.

If you want to use A in your code managed by spring then you have to create yourself a factory for A :

@Bean
public A a() {
    B b = new MyB();
    A a = new A(b); // new A is not possible since A is abstract but you got the idea
    return a;
}

// ...

class MyService {
   @Autowired
   A a;

   void something() {
      (a.b instanceof MyB) // true
   }

}

Upvotes: 3

Related Questions