Springboot自定义配置并注入到bean

    xiaoxiao2022-07-05  193

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

    最新回复(0)