如何使用spring-boot创建REST服务?

问题描述 投票:1回答:6

我正在使用spring-boot并且希望集成如下的简单REST服务。

    @Controller
    @RequestMapping("/content")
    public class MyServiceRest extends SpringBeanAutowiringSupport {
        @RequestMapping(method = RequestMethod.GET)
        public String test() {
            return "OK";
        }
    }

结果: localhost:8080/<app-name>/services/content显示"No service was found." 。 为什么?

我是否必须以某种方式明确发布服务?

也许是由于我的调度程序servlet?

@Bean
public ServletRegistrationBean dispatcherServletRegistration() {
    ServletRegistrationBean registration = new ServletRegistrationBean(new CXFServlet(), "/services/*");
    registration.setName(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
    return registration;
}
java spring rest spring-boot
6个回答
1
投票

由于您使用的是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 Boot中使用Spring MVC而添加的注释。 然后,您可以像在问题中一样定义控制器。


0
投票

您还应该为您的方法添加网址映射

@RequestMapping(方法= RequestMethod.GET,值=“ url_here”,尝试

@RequestMapping(method = RequestMethod.POST, value = "/",

0
投票

将具有控制器类的包添加到主类中的@Component扫描中,例如: @ComponentScan( basePackages = { "your.package.with.controller" } ) ,这是在spring未初始化(不知道)控制器时发生的


0
投票

在我当前使用的最新版本的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);
    }
}


0
投票

从当前的spring-boot.1.5.6 ,不需要使用cxf

只需将@RestController@GetMapping @RestController使用,并乐于访问localhost:8080/content

© www.soinside.com 2019 - 2024. All rights reserved.