Spring Boot 启动时修改上下文
为了让项目在启东时,加载到封装的JAR中的国际化文件
在封装JAR是增加以下配置类
可用于更改启动上下文中的信息
依赖
org.springframework.bootspring-boot-autoconfigure2.7.18
示例
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Set;
public class EnviromentAutoConfigration implements ApplicationContextInitializer, Ordered {
@Override
public int getOrder() {
return Integer.MAX_VALUE;
}
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
ConfigurableEnvironment environment = applicationContext.getEnvironment();
HashMap properties = new HashMap();
properties.put("spring.messages.basename", getMessagesBasenameProperty(environment));
MapPropertySource propertySource = new MapPropertySource("", properties);
environment.getPropertySources().addFirst(propertySource);
}
/*
*读取指定的国际化文件
*/
private static String getMessagesBasenameProperty(Environment environment) {
LinkedHashSet
resources目录下META-INF文件夹spring.factories文件配置指定类
#上下文,环境配置,这个会先读取 org.springframework.cloud.BootstrapConfiguration=xxx.EnviromentAutoConfigration #读取@Configuration注解的配置文件 org.springframework.boot.autoconfigure.EnableAutoConfiguration=
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。
