Spring自动装配不处理属于外部JAR中的类的字段

时间:2018-04-19 18:31:15

标签: java spring dependency-injection autowired

我是Spring的新手,因为我继承了另一家公司使用Spring 3.2.18开发的现有项目,我遇到了以下问题:

我正在处理应用程序A(应用程序A不在Web服务器上运行),它用作依赖项目B.我有源代码B,所以我构建它并将jar包含为maven依赖项。项目B包含Class_1,Interface_2和Class_2(实现Interface_2)。 Class_1在org.foo中,而Interface_2和Class_2在org.toot中。

在应用程序A中,我需要在TestClass中自动装配Class_1,如下所示:

TestClass.java

@ContextConfiguration(locations={"file:src/test/spring/app-beans.xml"})
public class TestClass{
        @Autowired
        Class_1 class1;

        // do stuff
}

应用-beans.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" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">


    <context:spring-configured />

    <context:annotation-config />

    <aop:aspectj-autoproxy />

    <context:component-scan base-package="org.foo" />
    <context:component-scan base-package="org.toot" />

    <bean id="class_1" primary="true" class="org.foo.Class_1"/>

</beans>

现在问题是项目B中的Class_1也有一个自动装配的字段: 的 Class_1.java

@Service
public class Class_1 {

@Autowired
Interface_2 int2;

}

Interface_2.java

public interface Interface_1 {

// stuff

}

Class_2.java

@Service
public class Class_2 implements Interface_2{

// stuff

}

每当我尝试运行我的TestClass时,我都会收到以下错误:

Could not autowire field: private org.foo.Class_1;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [org.toot.Interface_1]
found for dependency [...]: expected at least 1 bean which qualifies as autowire candidate for this dependency. 

我从中获得的是它以某种方式尝试自动装配Class_1但不能自动装配Interface_2以使其失败。如何将Interface_2(Class_2)的实现自动连接到Class_1字段?项目B没有任何弹簧上下文文件。我可以修改项目A中的app-beans.xml来实现它吗?我是否必须在项目B中包含上下文文件并重新构建?请分享您的知识并感谢您的阅读。

0 个答案:

没有答案