[英]java @Inject annotation returns null
I am trying to inject a method from another class, but it returns null and throws a NullPointerException.我试图从另一个类注入一个方法,但它返回 null 并抛出一个 NullPointerException。 Please let me know what mistake am I doing here.
请让我知道我在这里做错了什么。
import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("/")
public class Employee {
@Inject
EmployeeService employeeService;
@GET
@Path("/empXml")
@Produces({ "application/xml" })
@RolesAllowed({"employee"})
public String getHelloWorldXML() {
return "<xml><result>" + employeeService.createHelloMessage("Employee") + "</result></xml>";
}
public static void main(String[] args){
Employee em=new Employee();
System.out.println(em.getHelloWorldXML()); //gives NPE
}
}
public class EmployeeService {
int x = 10;
String createHelloMessage(String name) {
return "Hello " + name + "!";
}
}
I added bean.xml file to my project's WEB-INF folder.我将 bean.xml 文件添加到我项目的 WEB-INF 文件夹中。 And that solved the issue.
这解决了这个问题。
beans.xml bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
<!-- An application that uses CDI must have a file named beans.xml.
The file can be completely empty (it has content only in certain
limited situations), but it must be present. -->
</beans>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.