Search code examples
springspring-bootcdi

javax.inject.Inject beans not recognized in Spring boot


I have an external dependency (added as dependency in pom.xml) which uses dependency injection using CDI (javax.inject.Inject) in my spring boot app. I'm trying to Autowired one those CDI managed bean but had no luck.

I keep getting below error.

No qualifying bean of type '<Bean name>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

I tried ComponentScan to scan the CDI managed bean but it doesn't help either.

Could someone help on how to get Spring boot aware of the CDI managed beans


Solution

  • You need to create an instance of your bean that Spring manages.

    In Java code you could do this (notice this works for any class, even if it's from a 3rd party library you don't control):

    @Configuration
    public class Config {
        @Bean
        public MyBean myBean() {
            // Return a new instance of your class here
            return new MyBean();
        }
    }
    

    Or in XML:

    <beans>
        <bean id="myBean" class="abc.def.MyBean"/>
    </beans>
    

    Now you can inject MyBean using either @Inject or Spring's @Autowired annotation.