I am trying to inject a method from another class, but it returns null and throws a 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. And that solved the issue.
beans.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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.