java @Inject注释返回null

时间:2015-10-08 14:14:18

标签: java

我正在尝试从另一个类注入一个方法,但它返回null并抛出一个NullPointerException。请让我知道我在这里犯了什么错误。

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 + "!";
    }

}

1 个答案:

答案 0 :(得分:1)

我将bean.xml文件添加到项目的WEB-INF文件夹中。这解决了这个问题。

的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>