Bharath
Bharath

Reputation: 15

How to inject an interface non managed by spring into a spring component

im relatively new to spring framework and facing a challenge currently.

I have an interface ABC from an external library with me and a class BCD. Now, i need to use ABC in my class. But when i autowire it, it always comes as null and throws NPE. ABC is not annotated.

Constructor in BCD required a bean of type ABC that could not be found.

Please let me know if this is something that is poosible with spring & guide me in the right direction!!

Note - This is not inject spring bean in non-spring managed bean but the other way around. ABC is not managed by spring and BCD is a @Component class.

Thanks in Advance!!

import SampleInterface from from a maven dependency

@Component
public class ABC {
    
    @Autowire
    private SampleInterface SI;

    // Do my stuff
}

Upvotes: 1

Views: 1737

Answers (1)

Rob Spoor
Rob Spoor

Reputation: 9175

You should have a class that's annotated with @Configuration (a new one or an existing one). In that class, add a method that returns an instance of ABC and annotate that method with @Bean. This will turn the return value into a Spring bean that you can then inject anywhere.

Upvotes: 3

Related Questions