Spring Boot 启动时修改上下文
Spring Boot 启动时修改上下文
- 为了让项目在启东时,加载到封装的JAR中的国际化文件
- 在封装JAR是增加以下配置类
- 可用于更改启动上下文中的信息
- 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.7.18</version>
</dependency>
- 示例
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<ConfigurableApplicationContext>, Ordered {
@Override
public int getOrder() {
return Integer.MAX_VALUE;
}
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
ConfigurableEnvironment environment = applicationContext.getEnvironment();
HashMap<String, Object> 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<Object> basenames = new LinkedHashSet<>();
String basenameString = environment.getProperty("spring.messages.basename");
if (StringUtils.isNoneBlank(basenameString)) {
basenames.addAll(Set.of(basenameString.split(",")));
}
basenames.add("messages/xxx_messages");
return String.join(",",basenames);
}
}
resources
目录下META-INF
文件夹spring.factories
文件配置指定类
#上下文,环境配置,这个会先读取
org.springframework.cloud.BootstrapConfiguration=xxx.EnviromentAutoConfigration
#读取@Configuration注解的配置文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=