【发布时间】:2021-11-13 21:35:47
【问题描述】:
最近我尝试了 Tomcat 10.0.10,当尝试将连接池作为 JNDI 资源注入时,发现 @Resource 注释不起作用。
然后我尝试通过创建InitialContext 以编程方式获取它,并且它起作用了。最初我认为它仅适用于 java:comp/env/jdbc,所以我尝试使用如下所示的简单 bean,并尝试使用 @Resource 注释注入它,但它不再起作用。当我尝试通过创建InitialContext 以编程方式获取它时,它可以工作。然后我检查 @PostConstruct 或 @PreDestroy 注释是否有效,发现它们也不起作用。
package lk.ijse.test.tomcatdbcp;
public class Something {
}
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="bean/Something" auth="Container"
type="lk.ijse.test.tomcatdbcp.Something"
factory="org.apache.naming.factory.BeanFactory"
/>
</Context>
<?xml version="1.0" encoding="UTF-8"?>
<web-app metadata-complete="false" xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<resource-env-ref>
<resource-env-ref-name>bean/Something</resource-env-ref-name>
<resource-env-ref-type>lk.ijse.test.tomcatdbcp.Something</resource-env-ref-type>
</resource-env-ref>
</web-app>
package lk.ijse.test.tomcatdbcp;
import java.io.*;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;
@WebServlet(name = "helloServlet", value = "/hello", loadOnStartup = 1)
public class HelloServlet extends HttpServlet {
private String message;
@Resource(name= "java:comp/env/bean/Something")
private Something something;
@PostConstruct
public void doSomething(){
System.out.println("Does it work?");
}
public void init() {
message = "Hello World!";
try {
InitialContext ctx = new InitialContext();
Something lookup = (Something) ctx.lookup("java:comp/env/bean/Something");
System.out.println(lookup);
System.out.println(something); // null
} catch (NamingException e) {
e.printStackTrace();
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
// Hello
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>" + message + "</h1>");
out.println("</body></html>");
}
public void destroy() {
}
}
为了重现同样的问题,我在这里创建了一个示例 repo:https://github.com/sura-boy-playground/play-with-tomcat10 (完整的代码可以在那里找到)
起初,我使用了javax.annotation.Resource 注解,所以我认为这是因为javax.* 到jakarta.* 命名空间发生了变化。然后我用jakarta.annotation.Resource试了一下,结果还是一样。
我用 Tomcat 9.0.41 加上 javax.* 命名空间尝试了相同的应用程序,它运行良好。
我需要在 Tomcat 10.0.10 上做任何额外的事情来启用这些注释吗?我挖掘了 Tomcat 10 文档,但我找不到任何与我的问题。
我发现之前在 Tomcat 7 中也有类似的情况,但我现在不喜欢这种解决方法。 Tomcat @Resource annotations API annotation stops working in Tomcat 7
【问题讨论】:
标签: java tomcat servlets jakarta-ee