BrianP BrianP - 1 year ago 175
Java Question

How can I @Autowire a spring bean that was created from an external jar?

I have a module/jar that I've created and am using as a util library. I created a service in there like so:

public class PermissionsService { ... }

... where this resides in a package here: com.inin.architect.permissions and in my main application, I'm referencing/loading this jar (i.e. set as a dependency in the maven POM.xml file for the app) like so:


and within the application I want to use that service like:

PermissionsService permissions

In the application's spring setup, I've got this:

@ComponentScan(basePackages = { "com.inin.generator", "com.inin.architect.permissions" })
public class WebConfig extends WebMvcConfigurerAdapter implements ServletContextAware { }

However when I run my application under tomcat, it complains that there isn't a bean for the PermissionsService: "org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ..."

So, how can I bring over the bean from the lib into my application? Surely there's a way. Do you have to set the library up as a full blown spring MVC application so that this can work? i.e. do you have to have @Configuration and @ComponentScan setup in the lib as well?

Answer Source

You have to scan at least the package containing the class you want to inject. For example, with Spring 4 annotation:

class Config {

It is the same principle for XML configuration.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download