【发布时间】:2013-07-16 08:28:14
【问题描述】:
我正在尝试使用 Spring 构建一个独立的应用程序(不在应用程序服务器中运行),但我遇到了以下问题:
我的独立应用程序(启用了 spring)依赖于另一个项目(捆绑为一个 jar),该项目在 com.application.service 中包含很多服务(用 @Service 注释)。
外部项目中没有spring相关的配置,独立应用上下文很简单,只包含:
<context:component-scan base-package="com.application" />
这是一个依赖于无法获取的服务的类的示例:
@Service
public class StandaloneService {
@Autowired
private SomeService someService;
// ...
}
StandaloneService 包含在独立应用程序中,而SomeService 包含在外部 jar 中。
错误:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.application.SomeService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
这是我创建ApplicationContext 并尝试获取我的服务的方式:
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });
BeanFactory factory = (BeanFactory) context;
StandaloneService standalone = factory.getBean(StandaloneService.class);
}
我如何构建独立应用程序:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<index>true</index>
<manifest>
<classpathPrefix>./lib/</classpathPrefix>
<addClasspath>true</addClasspath>
<mainClass>com.application.Main</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>false</overWriteSnapshots>
<overWriteIfNewer>true</overWriteIfNewer>
</configuration>
</execution>
</executions>
</plugin>
我如何运行它(导致失败):
java -jar target/standalone.jar
奇怪的是,如果我以这种方式运行它,它可以工作:
mvn "-Dexec.args=-classpath %classpath com.application.Main" -Dexec.executable=/usr/lib/jvm/java-7-openjdk/bin/java -Dexec.classpathScope=runtime process-classes org.codehaus.mojo:exec-maven-plugin:1.2.1:exec
谁能帮我弄清楚为什么 Spring 在第一种情况下看不到我的外部服务?
编辑
这是来自外部 jar 的 pom.xml :
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addClasspath>true</addClasspath>
</manifest>
</archive>
</configuration>
</plugin>
【问题讨论】:
-
我使用用于创建外部 jar 的 pom.xml 的相关部分编辑了我的问题。我添加了
<configuration>部分,但这并没有改变我的问题。我没有使用 eclipse 而是使用 netbeans,但我希望它能够在任何 IDE 的范围内工作。
标签: spring maven classpath classloader