user2914191
user2914191

Reputation: 897

spring boot scanning and injecting external non-spring beans

What does it take, or is it even possible for Spring to scan and inject non-spring annotated classes? For example.

resource.jar

com.project.resource.ResourceInterface
com.project.resource.StandardResource <-- concrete implementation

@Singleton <--- Standard CDI annotation
public class StandardResource implements ResourceInterface{
    @Override
    public void something(){}
}

Now let's say I have a spring boot application which depends on resource.jar.

com.project.resource.SpringApp

@SpringBootApplication(scanBasePackages = {"com.project"})
@EnableAutoConfiguration
public class SpringApp{
    ... initializer
    @Inject
    private ResourceInterface resourceService; <--- this is not found
}

Is this supposed to work out of the box? Is this even possible? I'm using spring boot 2.0.0.RELEASE. I'm getting the following error:

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'MainController': Unsatisfied dependency expressed through field 'resourceService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.project.resource.ResourceInterface' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.inject.Inject()}

Thanks

Upvotes: 0

Views: 1051

Answers (1)

dev4Fun
dev4Fun

Reputation: 1050

For Spring framework @Singleton has no meaning, as such even if class is picked up by component scanning it's going to be ignored. In order for Spring to recognize your class you can:

  • Create a configuration class in com.project.resource with @Bean of
    ResourceInterface and instantiate it as StandardResource.
  • Since you are using Spring Boot you can create Auto-configuration (which will be similar to the first option) in resource.jar. You can follow examples from creating autoconfiguration. With this approach no changes needed in com.project.resource

After that your spring boot app will run normally

Upvotes: 2

Related Questions