springboot启动时读取配置文件并赋值

最近做的项目中,有一个步骤是要写一个用来进行和其他东西进行连接的对象。

这个连接对象用static修饰,并直接调用一个方法初始化。

public static THPLCLibrary THPLC = THPLCLibrary.instance(参数);

这样就可以在springboot启动的时候就给这个连接对象初始化了。
但是方法里面的参数还是想从配置文件读取的,不想写死。
但是单纯的使用@value注解并没有起作用,感觉是因为在springboot启动时,初始化静态变量在加载配置文件之前,所以没有获取到配置文件中的内容。
查了一番资料,发现可以这么做:

写一个配置类,使用@ConfigurationProperties注解,将配置文件里的内容作为静态属性。在下面只写set方法,并使用@value注解。
然后在springboot的启动类中添加
@EnableConfigurationProperties({配置类.class})
这个注解就可以了,示例代码如下:

配置文件 application.yml:

thplcconfig:
  TPath:
    F:\code\src\main\resources\aaa
  THPLCServerAddress:
    127.0.0.1
  THPLCServerPort:
    10000

配置类:

@Component
@ConfigurationProperties(prefix = "thplcconfig")
public class THPLCConfig {
    public static String THPLCServerAddress;

    public static Integer THPLCServerPort;

    public static String TPath;

    @Value("${thplcconfig.TPath}")
    public void setTPath(String TPath) {
        THPLCConfig.TPath = TPath;
    }

    @Value("${thplcconfig.THPLCServerAddress}")
    public  void setTHPLCServerAddress(String THPLCServerAddress) {
        THPLCConfig.THPLCServerAddress = THPLCServerAddress;
    }
//
    @Value("${thplcconfig.THPLCServerPort}")
    public  void setTHPLCServerPort(Integer THPLCServerPort) {
        THPLCConfig.THPLCServerPort = THPLCServerPort;
    }
}

启动类:

@EnableConfigurationProperties({THPLCConfig.class})
public class AppRun {

    public static void main(String[] args) {
        SpringApplication.run(AppRun.class, args);
    }

使用的时候直接类名.属性名就可以使用:

public static THPLCLibrary THPLC = THPLCLibrary.instance(THPLCConfig.THPLCServerAddress,THPLCConfig.THPLCServerPort,THPLCConfig.TPath);

注意:
1,在@value注解中的配置要从最外到内写全,比如上面代码,ConfigurationProperties中写了prefix = “thplcconfig”,但是下面@value的时候,也要写成"${thplcconfig.TPath}" 而不是"${TPath}",写不全的话会报错取不到值。
2,下方的set方法不要使用static来修饰,快捷键生成的set方法里面是带static的,那样会取不到值。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值