简体   繁体   中英

Can I represent a runnable Spring boot restlet application as a servlet?

I have a nicely working Spring Boot restlet application which is currently a stand alone executable with not too much startup code:

@SpringBootApplication
@EnableJpaRepositories(basePackageClasses = { MelonRepository.class })
@EnableTransactionManagement
public class Runner {

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

I also have a number of restlets that all look like

@RestController
@RequestMapping(value = "/here", produces = "application/json")
public class TheController {

  @Autowired
  protected Business processor;

  @RequestMapping(value = "/{accoId}")
  public Something findSomethingByAccoId(@PathVariable String id) {

  (...)

I do not have my own XML at the moment, everything is configured using annotations.

However while the app runs nicely standalone, I got a requirement to make it a part of the legacy .war application in a way such that it could be configured with other (legacy) servlets inside the shared web.xml (already exists).

How to wrap the Spring Boot restlet into a "normal" servlet to be deployed along other "normal" servlets?

The way to do is through the org.springframework.web.servlet.DispatcherServlet that is a servlet exactly for this purpose. If you want to configure it through annoations, the corresponding web.xml fragment looks like

<servlet>
    <servlet-name>myservlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextClass</param-name>
        <param-value>
        org.springframework.web.context.support.AnnotationConfigWebApplicationContext
    </param-value>
    </init-param>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
           com.mine.config.WebConfiguration
    </param-value>
    </init-param>
</servlet>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring-core-config.xml</param-value>
</context-param>

where spring-core-config.xml may include additional context:component tags (to scan packages of the required annotated components) or message converters or anything else.

com.mine.config.WebConfiguration is assumed to be your annotation-based web configuration class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM