簡體   English   中英

java @Inject 注解返回 null

[英]java @Inject annotation returns null

我試圖從另一個類注入一個方法,但它返回 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 + "!";
    }

}

我將 bean.xml 文件添加到我項目的 WEB-INF 文件夾中。 這解決了這個問題。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM