您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Spring-Boot:如何添加tomcat连接器以绑定到控制器

Spring-Boot:如何添加tomcat连接器以绑定到控制器

您可以为每个服务使用子应用程序,并通过设置其server.port属性将每个子应用程序配置为使用单独的端口。您想要隔离的任何组件都应该放在其中一个子组件中。您要共享的任何组件都应放在父组件中。

这是此方法的示例。有两个子应用程序,一个监听端口8080,另一个监听端口8081。每个子应用程序都包含一个分别映射到/one和的控制器/two

package com.example;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

public class Application {

    public static void main(String[] args) {
        SpringApplicationBuilder parentBuilder 
                = new SpringApplicationBuilder(ApplicationConfiguration.class);
        parentBuilder.child(ServiceOneConfiguration.class)
                .properties("server.port:8080").run(args);
        parentBuilder.child(ServiceTwoConfiguration.class)
                .properties("server.port:8081").run(args);      
    }

    @Configuration
    static class ApplicationConfiguration {

        @Bean
        public MySharedService sharedService() {
            return new MySharedService();

        }   
    }

    @Configuration
    @EnableAutoConfiguration
    static class ServiceOneConfiguration {

        @Bean
        public ControllerOne controller(MySharedService service) {
            return new ControllerOne(service);
        }
    }

    @Configuration
    @EnableAutoConfiguration
    static class ServiceTwoConfiguration {

        @Bean
        public ControllerTwo controller(MySharedService service) {
            return new ControllerTwo(service);
        }
    }

    @RequestMapping("/one")
    static class ControllerOne {

        private final MySharedService service;

        public ControllerOne(MySharedService service) {
            this.service = service;
        }

        @RequestMapping
        @ResponseBody
        public String getMessage() {
            return "ControllerOne says \"" + this.service.getMessage() + "\"";
        }
    }

    @RequestMapping("/two")
    static class ControllerTwo {

        private final MySharedService service;

        public ControllerTwo(MySharedService service) {
            this.service = service;
        }

        @RequestMapping
        @ResponseBody
        public String getMessage() {
            return "ControllerTwo says \"" + this.service.getMessage() + "\"";
        }
    }

   static class MySharedService {

        public String getMessage() {
            return "Hello";
        }
    }
}
Java 2022/1/1 18:14:26 有510人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶