spring boot 通过继承PropertyPlaceholderConfigurer,获取配置文件中的配置项
时间: 2024-02-21 21:00:27 浏览: 21
在Spring Boot中,可以通过继承PropertyPlaceholderConfigurer类来获取配置文件中的配置项。
首先,创建一个类,继承自PropertyPlaceholderConfigurer,重写processProperties方法,该方法在Spring应用程序上下文启动时会被调用,可以在该方法中获取配置文件中的属性值,例如:
```java
public class MyPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
private Properties properties;
public MyPropertyPlaceholderConfigurer() {
this.properties = new Properties();
}
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
super.processProperties(beanFactoryToProcess, props);
this.properties.putAll(props);
}
public String getProperty(String key) {
return this.properties.getProperty(key);
}
}
```
在该类中,我们重写了processProperties方法,并在该方法中将配置文件中的属性值保存到一个Properties对象中。然后,提供了一个getProperty方法,可以根据属性名获取属性值。
接下来,在Spring Boot启动类中,注入该类的实例,并通过该实例获取配置文件中的属性值,例如:
```java
@SpringBootApplication
public class MyApp {
@Autowired
private MyPropertyPlaceholderConfigurer propertyConfigurer;
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
@PostConstruct
public void init() {
String propertyValue = propertyConfigurer.getProperty("my.property");
System.out.println("my.property value is: " + propertyValue);
}
}
```
在上述代码中,我们通过@Autowired注入了MyPropertyPlaceholderConfigurer实例,并在init方法中,获取了配置文件中的属性值,并打印出来。
在application.yml或application.properties中,可以定义my.property属性值,例如:
```yaml
my.property: my custom property value
```
这样,当应用启动时,就会打印出"my.property value is: my custom property value"。