嗨,我想通过 spring mvc 处理 Web 请求并通过 Jersey 处理休息
在同一个项目中(Spring-Boot)
当我测试 Rest 服务正在工作但网络不是
如何设置应用程序配置?
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackageClasses = {ProductsResource.class, MessageService.class,Web.class})
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Bean
public ServletRegistrationBean jerseyServlet() {
ServletRegistrationBean registration = new ServletRegistrationBean(new ServletContainer(), "/rest/*");
registration.addInitParameter(ServletProperties.JAXRS_APPLICATION_CLASS, JerseyInitialization.class.getName());
return registration;
}
@Bean
public ServletRegistrationBean webMVC() {
DispatcherServlet dispatcherServlet = new DispatcherServlet();
AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
applicationContext.register(ResourceConfig.class);
dispatcherServlet.setApplicationContext(applicationContext);
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(dispatcherServlet, "*.html");
servletRegistrationBean.setName("web-mvc");
return servletRegistrationBean;
}
网页 Controller
@Controller
@Component
public class Web {
@RequestMapping("/foo")
String foo() {
return "foo";
}
@RequestMapping("/bar")
String bar() {
return "bar";
}
}
休息 Controller
@Path("/")
@Component
public class ProductsResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/hello")
public String hello() {
return "Hello World";
}
}
最佳答案
实际上,使用 spring boot(我说的是 1.4.x 版),同时执行 Spring MVC 和 JAX-RS( Jersey 休息)非常容易:)。您不需要任何 servlet 注册。您需要做的就是添加一个 Configuration
类如下
@Configuration
@ApplicationPath("/rest")
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
packages("your.package.with.rest.resources");
}
}
现在您所有的 JAXRS 资源都在
/rest/*
下提供服务例如,您的 Rest Controller 可以重构为
@Path("/hello")
@Component
public class ProductsResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public String hello() {
return "Hello World";
}
}
现在,如果你点击 url
http://server:port/rest/hello
, Hello World 应该被退回。最后记得在你的maven pom文件中添加以下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
那应该对你有用。
关于rest - 如何在 spring boot 中使用 "web request by spring mvc"和 "rest by jersey",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32392170/