我对CDI中的构造方法注入有疑问。现场或属性注入效果很好。构造函数注入的字段注入实例也可以正常工作。唯一的方法不起作用-Servlet类中的构造函数注入。
配置:WEB-INF中的空bean.xml,在context.xml中定义的BeanManager。
环境:Tomcat 9.0.24,CDI,WELD实现。
示例代码:
@WebServlet(urlPatterns = "/servlet/*")
public class SimpleServlet extends HttpServlet implements Serializable {
// @Inject
private TestService testService;
@Inject
public SimpleServlet(TestService testService) {
this.testService = testService;
}
// Without this constructor (even protected) I have Exception java.lang.NoSuchMethodException: SimpleServlet.<init>()
public SimpleServlet() {
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// This prints null when using constructor injection
// Prints instance hashcode when using field injection
resp.getWriter().write(testService + "");
}
@PostConstruct
public void onPostConstruct() {
System.out.println("This is invoked everytime");
// Null when constructor injection
System.out.println(testService);
}
}
POM.xml
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>8.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0.SP1</version>
</dependency>
<dependency>
<groupId>org.jboss.weld.servlet</groupId>
<artifactId>weld-servlet-shaded</artifactId>
<version>3.1.2.Final</version>
</dependency>
</dependencies>
您已经尝试降级CDI版本?尝试在pom.xml中更改这些依赖项。
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.jboss.weld.servlet</groupId>
<artifactId>weld-servlet</artifactId>
<version>2.2.9.Final</version>
</dependency>