美文网首页
Spring Tomcat启动前, 通过代码更改配置

Spring Tomcat启动前, 通过代码更改配置

作者: 清蒸三文鱼_ | 来源:发表于2021-07-25 16:22 被阅读0次

    背景

    本地测试时, 在同个project启动多个spring boot的进程, 同个application.properties无法分裂出不同的配置, 如进程启动的端口, 项目名称等信息; 当然有其他的方式来实现, 如在启动类里加入@PropertySource注解指定对应的配置文件, 这里不做讨论; 更多的方式可以自己去debug源码, 更改代码的位置需要配合Spring的类触发机制.

    实现方式

    • 1. SpringApplication初始化阶段加入ApplicationContextInitializer (推荐)

    使用这种方式的好处, 自由程度和优先级高, 可以先于run方法执行前, 如在tomcat启动前更改tomcat的配置, 如端口路径

    @SpringBootApplication
    public class TencentUserApp {
        public static void main(String[] args) {
            SpringApplication app = new SpringApplication(TencentUserApp.class);
            app.addInitializers((context) -> {
                HashMap<String, Object> map = new HashMap<>();
                map.put("server.port", 8081);
                String appName = "tencentUser";
                map.put("spring.application.name", appName);
                map.put("server.servlet.context-path", "/" + appName);
                map.put("eureka.instance.appname", appName);
                context.getEnvironment().getPropertySources()
                        .addFirst(new MapPropertySource("custom_props", map));
            });
            app.run(args);
        }
    }
    
    • 2. 启动前更改ServerProperties

    思路是更改ServerProperties, 继承TomcatWebServerFactoryCustomizer 是思路之一, 缺点是无法更改其他的配置

    public class TencentUserApp extends TomcatWebServerFactoryCustomizer {
        public TencentUserApp(Environment environment, ServerProperties serverProperties) {
            super(environment, serverProperties);
            serverProperties.setPort(7788);
        }
    }
    
    • 3. 实现ApplicationContextAware接口, 在ApplicationContext中更改

    这种方式可以更改配置, 但是无法在容器启动前更改, 因为需要依赖applicationContext

     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            ConfigurableEnvironment env = (ConfigurableEnvironment) applicationContext.getEnvironment();
            //方式1 env.getPropertySources() .addFirst(null);
            //方式2,使用replace方法或反射更改source内容
            PropertySource<?> application = env.getPropertySources().stream()
                    .filter(v -> v.getName().contains("application")).findAny().get();
        }
    
    debug
    • 4. 使用spring.factories自动装配

    参考boot的包, 里面涉及到很多初始化的类加载, 不做赘述


    相关文章

      网友评论

          本文标题:Spring Tomcat启动前, 通过代码更改配置

          本文链接:https://www.haomeiwen.com/subject/pzfimltx.html