Java 如何使用spring boot创建REST服务?
我正在使用Java 如何使用spring boot创建REST服务?,java,spring,rest,spring-boot,Java,Spring,Rest,Spring Boot,我正在使用springboot,希望集成一个简单的REST服务,如下所示 @Controller @RequestMapping("/content") public class MyServiceRest extends SpringBeanAutowiringSupport { @RequestMapping(method = RequestMethod.GET) public String test() { r
springboot
,希望集成一个简单的REST
服务,如下所示
@Controller
@RequestMapping("/content")
public class MyServiceRest extends SpringBeanAutowiringSupport {
@RequestMapping(method = RequestMethod.GET)
public String test() {
return "OK";
}
}
结果:两个localhost:8080//services/content
结果“未找到任何服务。”
。为什么?
我是否必须以某种方式显式发布服务
也许是因为我的调度器servlet
@Bean
public ServletRegistrationBean dispatcherServletRegistration() {
ServletRegistrationBean registration = new ServletRegistrationBean(new CXFServlet(), "/services/*");
registration.setName(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
return registration;
}
您还应该为您的方法添加url映射 @RequestMapping(method=RequestMethod.GET,value=“url\u here”, 试一试
将带有控制器类的包添加到主类中的
@Component
扫描中,如:@ComponentScan(basePackages={“your.package.with.controller”})
,当spring未初始化时会发生这种情况(不知道)控制器由于您使用的是Spring Boot,请通过添加正确的注释来确保应用程序的设置正确。例如
@EnableAutoConfiguration
@EnableWebMvc
@Configuration
@ComponentScan
/*
* Application Setups using Spring boot.
*/
public class Application{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@EnableWebMvc
是使用Spring-MVC和Spring-boot时要添加的注释。
然后您可以像在问题中一样定义控制器。在我目前使用的最新版本的Spring Boot中,web服务的地址是
http://localhost:8080/content
此外,我用于启动服务的类如下所示:
@ComponentScan("eu.buzea")
@EnableAutoConfiguration
@EnableTransactionManagement
@SpringBootApplication
public class Application{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
源代码
大摇大摆
**干杯*从当前的
弹簧靴开始。1.5.6
不要求使用cxf
只需将
@RestController
与@GetMapping
一起使用,并乐于访问localhost:8080/content
通常约定为localhost:8080/ApplicationName/content,试试看?不幸的是,同样的结果……您的错误从404改为404了吗"找不到服务'msg?是的,我注意到我配置了dispatcher servlet,因此将路径更改为../services/content
将为我提供正确的路径。无论如何,找不到服务…@Controller
是一个通用的Spring MVC注释,您需要使用@EnableWebMvc
注释您的配置类如果您想让Spring加载这些,请使用Spring Boot或Tomcat。如果您想让Spring Boot自动配置REST控制器,请通过@RestController
更改@Controller
注释,并在配置类中使用@EnableAutoConfiguration
。我尝试在方法级别添加显式映射,但没有成功rk或者。web.xml中dispatcher servlet的映射是什么?您的路径中也应该有。可能dispatcher有问题。我更新了上面的代码。@EnableWebMvc
是REST的要求吗?我到目前为止还没有这个注释。注释:我还没有设置那个注释。当然,我在classpa上有它是的,如果你想用spring boot设置MVC,这个注释是必要的。看看这个文档,如果我的应用程序配置已经扩展了SpringBootServletializer,那会怎么样?那么我也不能扩展RepositoryRestMVCCConfiguration
…试着运行应用程序ontext applicationContext=SpringApplication.run(Application.class,args);myservicestcontroller=applicationContext.getBean(myservicestest.class);
,如果在组件扫描中找不到错误的控制器
@ComponentScan("eu.buzea")
@EnableAutoConfiguration
@EnableTransactionManagement
@SpringBootApplication
public class Application{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}