【发布时间】:2015-08-06 05:45:45
【问题描述】:
我正在尝试通过自己覆盖 Application 类的 getSingletons 方法来初始化我的 Web 服务资源。我正在使用 Jboss EAP 6.0 应用服务器。下面是代码
@ApplicationPath("/rest")
public class MyApplication extends Application {
private final Set<Object> singletons = new HashSet<Object>();
public MyApplication() {
singletons.add(new StudentFacade());
}
@Override
public Set<Object> getSingletons() {
return null; // Accidentally kept it as null but still my webservice was working. Dont know how it was working.
}
}
@Path("student")
public class StudentFacade {
@Resource(lookup = "java:global/ejb-beginner-sessions-ear/ejb-beginner-sessions-impl/StudentServiceBean!com.ejb.beginner.sessions.api.StudentService")
private StudentService studentService;
private static final Logger LOGGER = Logger.getLogger(StudentFacade.class.getName());
@GET
@Path("list")
@Produces(MediaType.APPLICATION_JSON)
public Student getStudents() {
LOGGER.info("studentService: " + studentService);
return new Student();
}
}
然后我意识到 getSingletons 方法返回 null 并且想知道我的 web 服务是如何工作的。
我认为因为我没有返回单例,所以应用程序服务器正在自行初始化 Web 服务。所以我删除了@Resource 并使用了@Inject,我得到了一个 WELD 异常,说没有找到依赖项。
然后我将其更改为返回单例,然后@Resource 没有查找 ejb 并且 studentService 为空。所以我使用 InitialContext 来查找 ejb 并且它起作用了。
try {
InitialContext initialContext = new InitialContext();
StudentService studentService = (StudentService) initialContext
.lookup("java:global/ejb-beginner-sessions-ear/ejb-beginner-sessions-impl/StudentServiceBean!com.ejb.beginner.sessions.api.StudentService");
LOGGER.info("studentService1: " + studentService);
} catch (NamingException e) {
e.printStackTrace();
}
谁能告诉我
- 为什么应用服务器初始化webservice,尽管我返回null
- 当我返回 null 时,为什么 @Inject 失败并且只有 @Resource 工作。
- 当我返回单例时,为什么 @Resource 失败并且只有 InitialContext 有效。
【问题讨论】:
标签: java rest dependency-injection jax-rs java-ee-6