Springboot自定义配置并注入到bean

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

原文地址:https://www.cnblogs.com/telwanggs/p/13094974.html