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 注解注入,要使用如上方法

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值