简体   繁体   English

在Web应用程序中初始化自动装配成员所需的最低配置是什么?

[英]What's the minimal configuration needed to init an Autowired member in a web-app?

What's the minimal configuration needed to have the following class member to be initialized using the @Autowired annotations: 使用@Autowired批注初始化以下类成员所需的最低配置是什么:

public class A {
  @Autowired
  private B b;
  // ...
}

When invoking A a = new A(), I'd like b to be initialized from a predefined bean without the need to configure it in code. 当调用A a = new A()时,我希望从预定义的bean中初始化b ,而无需在代码中对其进行配置。

Probably some files are needed: A.java , web.xml , spring-context.xml (for configuring B) and jars (spring and a jar containing B). 可能需要一些文件: A.javaweb.xmlspring-context.xml (用于配置B)和jars (spring和包含B的jar)。

What's the minimal needed configuration and files content? 什么是最少需要的配置和文件内容?

Based on this post , I created the this project . 基于这篇文章 ,我创建了这个项目 Steps to have B initiated: 启动B的步骤:

  1. Download and extract the compressed folder. 下载并解压缩压缩的文件夹。
  2. Run mvn clean install . 运行mvn clean install
  3. Copy the war (spring-autowired-1.0-SNAPSHOT.war) from the target to a web server's webapps folder. 将war(spring-autowired-1.0-SNAPSHOT.war)从目标复制到Web服务器的webapps文件夹。
  4. Run the server. 运行服务器。 (for tomcat: ./catalina.sh run) (对于tomcat:./catalina.sh运行)
  5. Call the API and see B's hascode - curl -X GET http://localhost:8080/spring-autowired-1.0-SNAPSHOT/rest/a/a . 调用API并查看B的hascode- curl -X GET http://localhost:8080/spring-autowired-1.0-SNAPSHOT/rest/a/a
  6. See b is initialized - not null. 请参阅b已初始化-不为null。

The actual class: 实际课:

@Component
@Path("/a")
public class A {

    @Autowired
    B b;

    @GET
    @Path("/a")
    public String a() {
        return b.toString();
    }
}

* The difference between my implementation vs. mkyong's is that my pom has less dependencies and @Autowired member is not an interface. *我的实现与mkyong的实现之间的区别在于,我的pom具有更少的依赖性,并且@Autowired成员不是接口。

If for some reason you cant configure class A to be a bean in your application context you can have class A implement SpringBeanAutowingSupport. 如果由于某种原因您不能将A类配置为应用程序上下文中的bean,则可以让A类实现SpringBeanAutowingSupport。 This works in a web environment. 这在Web环境中有效。

The SpringBeanAutowingSupport default constructor looks up the application context from the request. SpringBeanAutowingSupport的默认构造函数从请求中查找应用程序上下文。 It then injects the dependencies. 然后注入依赖项。

public class A extends SpringBeanAutowiringSupport{
  @Autowired
  private B b;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM