[英]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.java , web.xml , spring-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的步骤:
mvn clean install
. mvn clean install
。 curl -X GET http://localhost:8080/spring-autowired-1.0-SNAPSHOT/rest/a/a
. curl -X GET http://localhost:8080/spring-autowired-1.0-SNAPSHOT/rest/a/a
。 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.