加载类路径中jar内的spring应用程序上下文文件

Abh*_*hek 28 spring dependency-injection classpath

我试图在我的java独立代码中使用ClassPathXmlApplicationContext来加载applicationContext.xml,它位于我的类路径中的jar文件中.

ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:**/applicationContext*.xml");
Run Code Online (Sandbox Code Playgroud)

applicationContext.xml条目如下,

 <bean id="myAdder" class="com.foo.bar.MyAdder">
        <property name="floatAdder" ref="floatAdder"/>        
    </bean>
Run Code Online (Sandbox Code Playgroud)

而且,当我尝试以这种方式加载bean时,我得到NoSuchBeanException.不能用这种方式加载bean吗?

jar文件作为maven依赖项添加到我的类路径中.当我在Eclipse中看到这个项目的Java Build Path时,我看到这个jar链接为M2_REPO /.../ ..

我假设我可以在jar文件中加载bean,因为jar就是这样的.我错过了什么吗?

谢谢,阿比

aba*_*ogh 35

这应该工作,我刚刚创建了2个项目并进行了检查.

项目A(使用STS创建的标准Maven项目)具有applicationContext.xmlsrc/main/resources.

pom.xml中:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.D</groupId>
<artifactId>A</artifactId>
<version>0.0.1-SNAPSHOT</version>

<properties>        
    <spring.version>3.0.5.RELEASE</spring.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
</dependencies>
</project>
Run Code Online (Sandbox Code Playgroud)

applicationContext.xml中:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="myAdder" class="com.foo.bar.MyAdder">
    <property name="foo" value="bar" />
</bean>

</beans>
Run Code Online (Sandbox Code Playgroud)

项目B:

pom.xml:与A相同,除了A作为依赖项添加:

<dependency>
   <groupId>org.D</groupId>
   <artifactId>A</artifactId>
   <version>0.0.1-SNAPSHOT</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

项目B中的Start.java:

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath*:**/applicationContext*.xml");

    MyAdder myAdder = (MyAdder) context.getBean("myAdder");
    System.out.println(myAdder.getFoo());
}
Run Code Online (Sandbox Code Playgroud)

首先安装mvn,然后在项目B中运行Start.