spring:我可以自动装配组件字段的字段吗?

时间:2012-11-28 16:39:26

标签: java spring autowired

假设:

@Component
class Foo {}

class Bar {
   @Autowired
   Foo foo;
}

@Component
class Zoo {
   Bar bar = new Bar();
}

如何设置Spring以自动装配foo实例中的字段bar

更具体地说,我可以指示spring在看到实例后将Bar视为bean。例如,尊重@PostConstruct注释?

3 个答案:

答案 0 :(得分:1)

您已手动设置,因为使用new您正在创建不受Spring IOC容器管理的对象。

它也不会尊重@PostContruct,因为该注释仅适用于由容器管理的bean。

答案 1 :(得分:0)

为什么不能

@Component
class Zoo {
    @Autowired
    Bar bar;
}

 @Component
 class Bar {
    @Autowired
    Foo foo;
 }

答案 2 :(得分:0)

Spring能够使用aspectj连接使用@Configurable注释的类进行编译时编织。在maven中(取自Roo创建的配置):

        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>aspectj-maven-plugin</artifactId>
            <version>1.2</version>
            <!-- NB: do not use 1.3 or 1.3.x due to MASPECTJ-90 and do not use 1.4 due to declare parents issue  -->
            <dependencies>
                <!-- NB: You must use Maven 2.0.9 or above or these are ignored (see MNG-2972) -->
                <dependency>
                    <groupId>org.aspectj</groupId>
                    <artifactId>aspectjrt</artifactId>
                    <version>${aspectj.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.aspectj</groupId>
                    <artifactId>aspectjtools</artifactId>
                    <version>${aspectj.version}</version>
                </dependency>
            </dependencies>
            <executions>
                <execution>
                    <goals>
                        <goal>compile</goal>
                        <goal>test-compile</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <outxml>true</outxml>
                <aspectLibraries>
                    <aspectLibrary>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring-aspects</artifactId>
                    </aspectLibrary>
                </aspectLibraries>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>

并在应用程序上下文中添加<context:spring-configured/>