问题描述
我创建了一个模块/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:
@Service
public class PermissionsService { ... }
... 在这里的一个包中:com.inin.architect.permissions 并且在我的主应用程序中,我正在引用/加载这个 jar(即设置为应用程序的 maven POM.xml 文件),如下所示:
... 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:
<dependency>
<groupId>com.inin.architect</groupId>
<artifactId>permissions</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
在应用程序中,我想使用该服务,例如:
and within the application I want to use that service like:
@Autowired
PermissionsService permissions
在应用程序的 spring 设置中,我有这个:
In the application's spring setup, I've got this:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.inin.generator", "com.inin.architect.permissions" })
public class WebConfig extends WebMvcConfigurerAdapter implements ServletContextAware { }
但是,当我在 tomcat 下运行我的应用程序时,它抱怨没有用于 PermissionsService 的 bean:org.springframework.beans.factory.NoSuchBeanDefinitionException: Noqualifying bean of type ..."
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 ..."
那么,如何将 lib 中的 bean 带入我的应用程序中?肯定有办法.您是否必须将该库设置为成熟的 Spring MVC 应用程序才能使其正常工作?即你必须在库中设置 @Configuration 和 @ComponentScan 吗?
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?
推荐答案
您必须至少扫描包含要注入的类的包.例如,使用 Spring 4 注解:
You have to scan at least the package containing the class you want to inject. For example, with Spring 4 annotation:
@Configuration
@ComponentScan("com.package.where.my.class.is")
class Config {
...
}
XML 配置原理相同.
It is the same principle for XML configuration.
这篇关于我如何@Autowire 一个从外部罐子创建的弹簧豆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!