springboot也用了有一個月了,因為業務需要自己自定義了一下Springboot配置,並且注入成功,再次記錄一下。
場景介紹,在配置文件里需要2個靜態文件路徑,分別對應本地和centos服務器的路徑,准備用一個bean的屬性控制路徑,當在業務里存文件時,根據profile對應的環境保存到相應位置。
解決方式:
先寫一個bean,加入到springboot的配置文件里,然后將這個bean注入到需要用到的類里,代碼如下
1.新建一個MyConfig類,並加上
@Component
@ConfigurationProperties(prefix="my.config")
這2個注解
@Component
@ConfigurationProperties(prefix="my.config")
public class MyConfig {
/**
* 靜態文件路徑
*/
private String staticLocation;
public String getStaticLocation() {
return staticLocation;
}
public void setStaticLocation(String staticLocation) {
this.staticLocation = staticLocation;
}
}
2.在Application里加上注解
@EnableConfigurationProperties(MyConfig.class)
使上面的類可以起作用
3.修改springboot配置文件
---
spring:
profiles: local
resources:
static-locations: file:${my.config.static-location}
my:
config:
static-location: D:/java/static/
---
spring:
profiles: dev
resources:
static-locations: file:${my.config.static-location}
my:
config:
static-location: /usr/static/
---
這里將my.config.static-location作為變量使用
3.注入到工具類里
@Component
public class WxUtil {
private static Logger logger = LoggerFactory.getLogger(WxUtil.class);
private static WxUtil wxUtil;
private final MyConfig myConfig;
public WxUtil(MyConfig myConfig) {
this.myConfig = myConfig;
}
@PostConstruct
public void init(){
wxUtil = this;
}
//然后編寫方法,用 wxUtil.myConfig.getStaticLocation() 獲得配置文件里配置的值
}
這里注意不能直接用 @Autowired 注解注入,要使用如上方法
————————————————
版權聲明:本文為CSDN博主「Honins」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/Honnyee/article/details/90447767