java – 使用new关键字创建的Spring bean(@Component)中的自动装配

前端之家收集整理的这篇文章主要介绍了java – 使用new关键字创建的Spring bean(@Component)中的自动装配前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两个春豆如下:
@Component("A")
@Scope("prototype")
public class A extends TimerTask {

    @Autowired
    private CampaignDao campaignDao;
    @Autowired
    private CampaignManager campManger;
    A(){
        init_A();
       }
    }

由于旧的代码,我必须使用新的关键字来创建一个新的对象

@Component("B")
@Scope("prototype")
public class B{
     public void test(){
       A a = new A();
     }
}

运行时 – > A类中的spring bean是空的,我可以创建一个新的spring bean A的实例,还是使用自动装配吗?

解决方法

您的组件“A”不是由Spring容器创建的,因此依赖关系不会被注入.但是,如果您需要支持一些遗留代码(从您的问题可以看出),您可以使用@Configurable注释和构建/编译时间编织:
@Configurable(autowire = Autowire.BY_TYPE)
public class A extends TimerTask {
  // (...)
}

然后,Spring会将自动连线依赖关系注入到组件A中,无论是由容器本身实例化还是在新的代码中实例化.

例如,要使用maven插件设置构建时间编织,您必须:

>添加< context:spring-configured />到Spring应用程序上下文
>配置Maven AspectJ plugin

在构建插件部分:

<build>
  <plugins>
    <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>aspectj-maven-plugin</artifactId>
      <version>1.4</version>
      <configuration>
        <complianceLevel>1.6</complianceLevel>
        <encoding>UTF-8</encoding>
        <aspectLibraries>
          <aspectLibrary>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
          </aspectLibrary>
        </aspectLibraries>
        <!-- 
          Xlint set to warning alleviate some issues,such as SPR-6819. 
          Please consider it as optional.
          https://jira.springsource.org/browse/SPR-6819
        -->
        <Xlint>warning</Xlint>
      </configuration>
      <executions>
        <execution>
          <goals>
            <goal>compile</goal>
            <goal>test-compile</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

…和依赖项:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aspects</artifactId>
  <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjrt</artifactId>
  <version>1.6.11</version>
</dependency>

有关详细信息,请参阅Spring参考
http://static.springsource.org/spring/docs/current/spring-framework-reference/html/aop.html#aop-atconfigurable

原文链接:https://www.f2er.com/java/122185.html

猜你在找的Java相关文章