springboot配置文件中的属性读出来需要用静态变量接住

迁移一个老项目(SpringMVC)代码到SpringBoot的过程中遇到一个问题:需要将配置文件(application)中的属性读出来赋到一个静态变量上,故使用上图方式

在Spring Boot项目,将配置文件(通常是application.properties或application.yml)属性读取静态变量通常是在启动类(如@SpringBootApplication或@RestController)完成的。你可以使用`@Value`注解或者`Properties`类配合`Environment`接口来实现这一目标。 1. 使用`@Value`注解: ```java @Component public class AppConfig { @Value("${property.name}") private static String propertyName; // 可以通过getter方法访问静态变量 public static String getPropertyName() { return propertyName; } } ``` 在这个例子,`${property.name}`是配置文件的键,它的值会被自动注入到`propertyName`。 2. 使用`Properties`和`Environment`: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.Environment; @Component public class AppConfig { private static Properties properties; @Autowired public AppConfig(ApplicationContext context, Environment env) { this.properties = new Properties(); env.getPropertySources().forEach(ps -> ps.forEach((key, value) -> properties.setProperty(key, value))); } public static String getProperty(String key) { return properties.getProperty(key); } } ``` 这里,我们先注入`ApplicationContext`和`Environment`,然后遍历环境的所有属性源,将它们添加到`Properties`对象。 无论哪种方式,建议将配置管理封装成单例或工具类,以便在整个应用方便地获取配置信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_我走路带风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值