使用 Restful 和 CDI 协同工作的最佳方式是什么?
What is the best way to use Restful and CDI working together?
我尝试使用 CDI 和 Restful 一起构建一个项目(从 CDI bean 发布一个 Restful 服务)但是我找不到方法来做到这一点。
有人知道他们如何在没有 EJB 的情况下协同工作吗?
关于 Restful,我假设您指的是 Jax-RS。采取以下代码:
UserResource.java
此 class 实现 RESTful API 访问用例 GetUser 并返回其结果。
@Path("users")
@ApplicationScoped
public class UserResource {
@Inject
private GetUser getUser;
@GET
public Response getUser(@QueryParam("userId") String userId) {
return UserRepresentationMapper.toRepresentation(getUser.getUser(userId);
}
}
GetUser.java
GetUser 用例使用一些依赖项(这里是 UserService)来获取其数据并对其进行处理。
@ApplicationScoped
public class GetUser {
@Inject
private UserService userService;
public ApplicationUser getUser(String userId) {
// ...
}
}
并有 beans.xml
within your META-INF
(jar) or WEB-INF
(war) directory to activate CDI (JEE6, beans.xml
is not needed when using JEE7 and all your classes are annotated with bean defining annotations).
我尝试使用 CDI 和 Restful 一起构建一个项目(从 CDI bean 发布一个 Restful 服务)但是我找不到方法来做到这一点。
有人知道他们如何在没有 EJB 的情况下协同工作吗?
关于 Restful,我假设您指的是 Jax-RS。采取以下代码:
UserResource.java
此 class 实现 RESTful API 访问用例 GetUser 并返回其结果。
@Path("users")
@ApplicationScoped
public class UserResource {
@Inject
private GetUser getUser;
@GET
public Response getUser(@QueryParam("userId") String userId) {
return UserRepresentationMapper.toRepresentation(getUser.getUser(userId);
}
}
GetUser.java
GetUser 用例使用一些依赖项(这里是 UserService)来获取其数据并对其进行处理。
@ApplicationScoped
public class GetUser {
@Inject
private UserService userService;
public ApplicationUser getUser(String userId) {
// ...
}
}
并有 beans.xml
within your META-INF
(jar) or WEB-INF
(war) directory to activate CDI (JEE6, beans.xml
is not needed when using JEE7 and all your classes are annotated with bean defining annotations).