我正在使用Java 1.7,Spring Framework 3.1和Jersey 1.8。
我创建了一个简单的类TeamData
通过localhost:8080/team/{id}
我可以从我的数据库中收到ID为{id}的团队名称。
@Path("team/")
public class TeamData {
@GET
@Path("{id}")
public Response getTeamById(@PathParam("id") int id) {
TeamServiceImpl teamServiceBean = getTeamServiceBean();
Team team = teamServiceBean.getTeamById(id);
output = "Team name : " + team.getTeamName();
return Response.status(200).entity(output).build();
}
/**
* Method gets bean from ApplicationContext
*/
public TeamServiceImpl getTeamServiceBean() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"bean-spring.xml");
TeamServiceImpl teamServiceBean = (TeamServiceImpl) applicationContext
.getBean("teamService", TeamServiceImpl.class);
return teamServiceBean;
}
}
如何在加载时初始化应用程序上下文?
有没有办法在Servlets中做点什么?
public class HelloServlet extends HttpServlet {
private ApplicationContext ac;
@Override
public void init() throws ServletException {
super.init();
ac = new ClassPathXmlApplicationContext("bean-spring.xml");
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO:
}
}
答案 0 :(得分:2)
您无需自己创建上下文。只需使用jersey-spring
集成模块即可。让泽西为你创造和维护它。
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-spring</artifactId>
<version>1.8</version>
</dependency>
您应该可以在Jersey资源类中@Autowired
提供{{1}}服务,没有任何问题。当然需要一些配置。
以下是一些完整的示例资源: