【发布时间】:2014-01-28 19:24:15
【问题描述】:
所以我尝试在基于 Felix 和 Maven 的 OSGi 包中创建远程 Rest (JSON) 服务。
我的基本服务接口:
@Controller
@RequestMapping("/s/fileService")
public interface RestFileService {
@RequestMapping(value = "/file", method = RequestMethod.POST)
@ResponseBody
public String getFile(Long id);
}
我的接口实现
public class RestFileServiceImpl implements RestFileService{
public String getFile(Long id) {
return "test service";
}
}
通常我会将其添加到我的 web.xml 中
<servlet>
<servlet-name>spring-mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc-dispatcher</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
这在普通的 web 应用程序中可以正常工作。 但现在我想把它放在一个 OSGi 包中。
Servlet 3.0 允许您使用@WebServlet 来声明一个没有 web.xml 的 servlet 所以我创建了一个 RestServlet
@WebServlet(value="/rest", name="rest-servlet")
public class RestServlet implements ServletContextListener {
private static Log sLog = LogFactory.getLog(RestServlet.class);
public void contextInitialized(ServletContextEvent arg0) {
sLog.info("initializing the Rest Servlet");
}
public void contextDestroyed(ServletContextEvent arg0) {
sLog.info("un-initializing the Rest Servlet");
}
}
这是我的 OSGi 激活器:
public class Activator implements BundleActivator {
private static Log sLog = LogFactory.getLog(Activator.class);
public void start(BundleContext context) throws Exception {
/*
* Exposing the Servlet
*/
Dictionary properties = new Hashtable();
context.registerService(RestFileService.class.getName(), new RestFileServiceImpl(), properties );
sLog.info("Registered Remote Rest Service");
}
public void stop(BundleContext context) throws Exception {
sLog.info("Unregistered Remote Rest Service");
}
}
我知道 Felix 有自己的使用 JAX 的 http 实现,但我试图用 spring 注释和尽可能少的 XML 来做到这一点。 我可以强制它注册注释驱动的 3.0 servlet 吗?
我做错了什么?这甚至可能吗?
【问题讨论】:
标签: java json spring rest osgi