How to create a REST endpoint in Spring Boot Java without @SpringBootApplication, using only XML file?

Viewed 367

I'm trying to implement a REST endpoint between two non-web applications with all configuration in XML files.
I've created a simple controller with a method that only returns "OK", so I can run some tests using Postman.
Unfortunately, the endpoint is not being created.

I did some research and I found out that I need to add the "context" tag with the component-scan pointing to the controller package for it to work.
But my current implementation is not enough for it to work:

<context:component-scan base-package="com.app.REST"/>

My controller class is:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TestController {

    @RequestMapping("/test")
    @ResponseBody
    public String test(){
        return "OK";
    }

}

My question is: is there any way to create a REST endpoint without annotating the main class with @SpringBootApplication? If yes, what am I missing? Is it something in my XML file or somewhere else?

1 Answers

For enabling the MVC functionality you need to instruct spring to scan for your controllers this is done via the <mvc:annotation-driven /> tag.

Also as the DispatcherServlet is taking care of your requests you need to add the correct configuration for it in your web.xml

....
<servlet>
        <servlet-name>my-dispatcher-servlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:web-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher-servlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

LE:

<mvc:annotation-driven> is similar to <context:component-scan> they register all beans annotated with @Controller, @Component, @Service, @Repository and @Bean...

The main difference with mvc:annotation-driven is that it also creates some extra beans which take care of the endpoint registration in the dispatcherServlet (the HandlerMapping, HandlerAdapters and some default conversionServices needed to represent your data received in your controllers for example)

Related