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=
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论