如何通过代码获取application.properties
时间: 2023-05-09 22:02:52 浏览: 50
在Spring Boot中,我们可以使用 @Value 注解来获取 application.properties 中的值,如下所示:
1. 首先,在配置类中添加 @PropertySource 注解,指定 application.properties 文件的位置:
```
@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
//...
}
```
2. 然后,在需要获取值的地方使用 @Value 注解:
```
@Component
public class MyComponent {
@Value("${my.property}")
private String myProperty;
//...
}
```
其中,“${my.property}” 就是 application.properties 文件中定义的属性名。这样就可以通过代码获取 application.properties 中的值了。
另外,如果需要获取所有的属性值,可以使用 Spring 的 Environment 对象,如下所示:
```
@Autowired
private Environment env;
public void someMethod() {
String myProperty = env.getProperty("my.property");
//...
}
```
此外,还可以在配置类中使用 @ConfigurationProperties 注解来一次获取全部属性值,如下所示:
```
@Configuration
@ConfigurationProperties(prefix = "my")
public class AppConfig {
private String property1;
private int property2;
//...
//Getter and Setter
}
```
在这种情况下,应用程序可以使用 AppConfig 对象的属性来访问 application.properties 文件中的所有属性。