How to create a REST service with spring-boot?

2019-08-05 13:59发布

问题:

I'm using spring-boot and want to integrate a simple REST service as follows.

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

Result: both localhost:8080/<app-name>/services/content results "No service was found.". Why?

Do I have to explicit publish the service somehow?

Maybe it is due to my dispatcher servlet?

@Bean
public ServletRegistrationBean dispatcherServletRegistration() {
    ServletRegistrationBean registration = new ServletRegistrationBean(new CXFServlet(), "/services/*");
    registration.setName(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
    return registration;
}

回答1:

Since you are using Spring Boot, make sure that your application is correctly setup by adding the correct annotations. For instance,

@EnableAutoConfiguration
@EnableWebMvc
@Configuration
@ComponentScan
/*
 * Application Setups using Spring boot.
 */
public class Application{

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@EnableWebMvc is the annotation to add for using Spring MVC with Spring boot. And then you can define your controller as you did in your question.



回答2:

add package with controller class to @Component scan in main class like: @ComponentScan( basePackages = { "your.package.with.controller" } ), this happens when spring didn't initialize (doesn't know about) controller



回答3:

you should also add url mapping for your method

@RequestMapping(method = RequestMethod.GET, value = "url_here", try

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


回答4:

In the latest version of Spring Boot, that I am currently using, the web Service would address be http://localhost:8080/content

Also, the class I use to launch the service looks as follows:

@ComponentScan("eu.buzea")
@EnableAutoConfiguration
@EnableTransactionManagement
@SpringBootApplication
public class Application{

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}


回答5:

Source Code

https://drive.google.com/open?id=0BzBKpZ4nzNzUWmJmOTFwbTFjWWM

using Swagger

http://localhost:7070/swagger-ui.html#/

**Cheers*



回答6:

As of current spring-boot.1.5.6 there is no requirement using cxf.

Just use a @RestController with @GetMapping, and be happy to access localhost:8080/content.