SpringBoot启动时如何通过Properties对象加载配置或直接传入属性?
SpringBoot 无文件系统依赖的配置加载与内存XML处理方案
一、通过Properties对象加载启动配置
1. 直接传入Properties到SpringApplicationBuilder
最直观的方式是在启动时构建Properties对象,通过SpringApplicationBuilder传入:
public static void main(String[] args) { Properties customProps = new Properties(); customProps.setProperty("server.port", "8081"); customProps.setProperty("spring.datasource.url", "jdbc:mysql://localhost:3306/test"); customProps.setProperty("spring.jpa.hibernate.ddl-auto", "none"); new SpringApplicationBuilder(YourApplication.class) .properties(customProps) .run(args); }
该方式会让传入的Properties优先级高于默认配置文件,若完全不想依赖文件,确保classpath下无application.properties/yml即可。
2. 自定义EnvironmentPostProcessor注入配置
如需在启动早期注入配置并覆盖默认逻辑,实现EnvironmentPostProcessor接口:
public class CustomConfigPostProcessor implements EnvironmentPostProcessor { @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { Properties props = new Properties(); props.setProperty("server.port", "8082"); props.setProperty("spring.datasource.username", "admin"); // 将自定义配置添加到环境最前面,确保优先级最高 environment.getPropertySources().addFirst( new PropertiesPropertySource("custom-runtime-props", props) ); } }
然后在META-INF/spring.factories中注册处理器:
org.springframework.boot.env.EnvironmentPostProcessor=com.yourpackage.CustomConfigPostProcessor
二、直接传入键值对配置
除了Properties对象,还可以直接传入键值对:
1. 通过Map设置默认属性
public static void main(String[] args) { SpringApplication app = new SpringApplication(YourApplication.class); Map<String, Object> defaultProps = new HashMap<>(); defaultProps.put("server.port", "8083"); defaultProps.put("spring.datasource.password", "123456"); app.setDefaultProperties(defaultProps); app.run(args); }
2. 链式传入字符串键值对
new SpringApplicationBuilder(YourApplication.class) .properties("server.port=8084", "spring.jpa.show-sql=true") .run(args);
三、覆盖默认配置加载逻辑,自定义属性读取器
1. 禁用默认配置文件加载
若要完全屏蔽application.properties/yml的加载,可在EnvironmentPostProcessor中移除默认的配置源:
@Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { MutablePropertySources sources = environment.getPropertySources(); // 移除默认配置文件对应的PropertySource sources.remove("applicationConfig: [classpath:/application.properties]"); sources.remove("applicationConfig: [classpath:/application.yml]"); // 添加自定义配置 Properties props = new Properties(); // ... 设置属性 sources.addFirst(new PropertiesPropertySource("custom-props", props)); }
2. 从内存字符串加载配置
无需文件,直接从内存字符串解析配置:
public class InMemoryConfigProcessor implements EnvironmentPostProcessor { @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { String configStr = """ server.port=8085 spring.datasource.url=jdbc:mysql://localhost:3306/test spring.jpa.hibernate.ddl-auto=update """; Properties props = new Properties(); try { props.load(new StringReader(configStr)); } catch (IOException e) { throw new RuntimeException("Failed to load in-memory config", e); } environment.getPropertySources().addFirst( new PropertiesPropertySource("in-memory-config", props) ); } }
注册方式同前,在spring.factories中添加该处理器即可。
四、内存字符串处理XML Bean配置
Spring支持从内存资源加载XML配置,可通过ByteArrayResource将字符串转换为Spring可识别的资源:
1. 通过ApplicationContextInitializer集成到SpringBoot
@SpringBootApplication public class YourApplication { public static void main(String[] args) { // 内存中的XML配置 String xmlBeanConfig = """ <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="userService" class="com.yourpackage.UserService"/> </beans> """; SpringApplication app = new SpringApplication(YourApplication.class); // 添加初始化器加载内存XML app.addInitializers(context -> { if (context instanceof GenericApplicationContext genericContext) { XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(genericContext); ByteArrayResource xmlResource = new ByteArrayResource( xmlBeanConfig.getBytes(StandardCharsets.UTF_8) ); reader.loadBeanDefinitions(xmlResource); } }); app.run(args); } }
2. 在配置类中直接加载内存XML
@Configuration public class XmlBeanConfig { @Bean public UserService userService() throws IOException { String xmlStr = "<bean id='userService' class='com.yourpackage.UserService'/>"; ByteArrayResource resource = new ByteArrayResource(xmlStr.getBytes()); XmlBeanFactory beanFactory = new XmlBeanFactory(resource); return (UserService) beanFactory.getBean("userService"); } }
内容的提问来源于stack exchange,提问作者Aaron Sims
相关产品推荐
相关产品推荐

