Search code examples
springmavenjavabeans

External Java Library issue with Autowiring and injecting bean


I have created a Spring Boot application managed by Maven. I'm retrieving an company's library from our Maven repository.

In this library, we have a service interface, not being annotated with '@Service':

public interface MyService {
   //...
}

This service has only one implementation :

public class DefaultMyService implements MyService {
   //...
}

This library context is managed the old Spring way (in applicationContext.xml file). I read that normally, Spring Boot is able to find the implementation if there's only one in the scope.

When I try to run "spring-boot:run" on my project, it will fail with the following error :

No qualifying bean of type 'com.pharmagest.saml.SAMLService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

I tried:

  1. To add a @ComponentScan on the configuration class, including packages in error : @ComponentScan(basePackages={"com.mycompany.web", "com.mycompany.thelibrary.client.*", "com.mycompany.thelibrary.services.*"})
  2. To add the bean definition in applicationContext.xml (if I add the interface it tells me it can define it, thus I heard that Spring can find the default implementation if there is only one ?)
  3. To add library at "runtime" in projects options
  4. To add the library as external resource not via maven

In all cases I just can maven build but can't run the project. Do you have any advice to help me ? thanks!


Solution

    1. Won't work as the DefaultMyService has no @Component (or @Service) annotation will not be detected.
    2. Bean definition has to be a concrete instance so use DefaultMyService instead of the interface. Spring will not detect anything for you your understanding is wrong
    3. and 4. Will not change anything only adding dependencies without proper 1. or 2. will do nothing.

    Just add a @Bean to your configuration

    @Bean
    public DefaultMyService myService() {
        return new DefaultMyService();
    }
    

    Or import the other libraries applicatiponContext.xml which is what you probably should do.

    @ImportResource("classpath:/applicationContext.xml")
    

    Add this next to the @SpringBootApplication.