SpringBoot——自定义start
在Spring Boot中,可以通过实现ApplicationContextInitializer
接口来自定义Spring应用上下文的初始化。
以下是一个简单的示例,演示如何创建一个自定义的ApplicationContextInitializer
:
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
public class CustomStartApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
ConfigurableEnvironment environment = applicationContext.getEnvironment();
MapPropertySource propertySource = new MapPropertySource("customStart", createCustomProperties());
environment.getPropertySources().addLast(propertySource);
}
private Map<String, Object> createCustomProperties() {
Map<String, Object> customProperties = new HashMap<>();
// 添加自定义属性
customProperties.put("custom.property.key", "customPropertyValue");
return customProperties;
}
}
要使用这个自定义的ApplicationContextInitializer
,你需要在Spring Boot应用的main
方法中传递它:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CustomStartApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(CustomStartApplication.class);
app.addInitializers(new CustomStartApplicationContextInitializer());
app.run(args);
}
}
在这个例子中,CustomStartApplicationContextInitializer
会在应用上下文初始化时向环境中添加一些自定义的属性。这些属性可以在Spring Boot的任何配置中使用,比如application.properties
、application.yml
或者通过@Value
注解。
评论已关闭