问题描述
我有一个模块/ jar我已经创建并用作util 库 。我在那里创建了一个服务:
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(即设置为app的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
在应用程序的弹簧设置中,我有这个:
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:没有类型的限定bean ...
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从lib中带到我的应用程序中?当然有办法。你是否必须将库设置为一个完整的弹簧MVC应用程序,以便这可以工作?即你是否必须在lib中设置@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一个从外部jar创建的spring bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!