This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Debug Note < How do @Autowire create spring beans from external JARS? >

Ask questions

I have a module/JAR created that I’m using as the util library. I created a service here, as follows:

@Service
public class PermissionsService {... }Copy the code

It is located in the location of the package: com. Inin. Architect. The permissions and application, my Lord I am reference/load the jar (i.e., set to the application of Maven POM. Dependencies in XML file).

Such as:

<dependency>
        <groupId>com.inin.architect</groupId>
        <artifactId>permissions</artifactId>
        <version>1.0 the SNAPSHOT</version>
    </dependency>
Copy the code

In the application, I want to use the service, for example:

@Autowired
PermissionsService permissions
Copy the code

I got the following information:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.inin.generator"."com.inin.architect.permissions" })
public class WebConfig extends WebMvcConfigurerAdapter implements ServletContextAware {}Copy the code

However, when I run my application in tomcat, it complained about no PermissionsService bean: “org. Springframework. Beans. Factory. NoSuchBeanDefinitionException: There is no qualified bean type.”

So, how do I introduce beans from the lib into my application?

Of course there is. Do you have to set up the library as a full Spring MVC application for it to work? That is, do you also have to install @Configuration and @ComponentScan in lib?

Answer a:

You must at least scan the package that contains the classes to be injected. For example, using Spring 4:

@Configuration
@ComponentScan("com.package.where.my.class.is")
class Config {... }Copy the code

Answer two:

Just a comment on this, but you can separate dependencies from Spring. Created in your @Configuration task

@Bean public PermissionsService  permissionsService(){
   return new PermissionsService()
}
Copy the code

This will also allow it to be injected. You don’t have to remove the Spring annotation, just an option to make it potentially available outside of Spring.

Answer three:

You can through the following ways in the main application import com. Inin. Architect. Application of permissions – context. The XML.

<import resource="classpath:/permissionApplicationContext.xml" />
Copy the code

This will enable you to define from com. Inin. Architect. Permissions automatic assembly bean.

The article translated from Stack Overflow: stackoverflow.com/questions/2…