SpringBoot 中 static 静态工具方法获取配置文件属性值

本文介绍了在Spring中如何使用`@PostConstruct`注解和实现`InitializingBean`接口来在项目启动时执行初始化方法,详细展示了代码示例,并提供了测试验证。这两种方式都在Spring容器初始化时执行自定义配置,设置静态变量。

一、使用 @PostConstruct 注解

 

1.1、原理

@PostContruct 是Java自带的注解,在方法上加该注解会在项目启动的时候执行该方法,也可以理解为在spring容器初始化的时候执行该方法。

1.2、代码

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @Configuration本质上还是@Component
 */
//@Configuration
@Component
public class NettyProtConfiguration {

    public static Integer coordinationProt;

    @Value("${netty.server.prot.coordination}")
    public Integer nettyServerProtCoordination;

    @PostConstruct
    public void setCoordinationProt() {
        coordinationProt = this.nettyServerProtCoordination;
    }
}

二、使用 InitializingBean

2.1、原理

当一个类实现这个接口之后,Spring启动后,初始化Bean时,若该Bean实现InitialzingBean接口,会自动调用afterPropertiesSet()方法,完成一些用户自定义的初始化操作。

2.2、代码

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Configuration本质上还是@Component
 */
//@Configuration
@Component
public class NettyProtConfiguration2 implements InitializingBean {

    public static Integer coordinationProt;

    @Value("${netty.server.prot.coordination}")
    public Integer nettyServerProtCoordination;

    @Override
    public void afterPropertiesSet() throws Exception {
        coordinationProt = this.nettyServerProtCoordination;
    }
}

三、测试

3.1、代码

import com.wangjing.socket.netty.NettyProtConfiguration;
import com.wangjing.socket.netty.NettyProtConfiguration2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = "com.wangjing")
public class SocketApplication {


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

        System.out.println("使用 @PostConcust注解的方式,获取常量的值:  " + NettyProtConfiguration.coordinationProt);
        System.out.println("使用 实现InitializingBean接口的方式,常量的值为:  " + NettyProtConfiguration2.coordinationProt);

    }

}
# 配置文件,yml 格式
netty: 
  server:
    prot:
      coordination: 8804

3.2、效果

注:以上内容仅提供参考和交流,请勿用于商业用途,如有侵权联系本人删除!

### 使用静态方法访问 `application.properties` 中的变量 为了在静态方法中引用 `application.properties` 文件中的变量,可以采用多种方式实现这一目标。一种常见的方式是在应用程序启动期间加载这些属性到内存中,并通过静态工具类提供便捷的方法获取它们。 下面展示了一个基于给定参考资料[^4] 的解决方案: #### 创建 Properties 工具类 创建名为 `PropertiesUtil.java` 的实用程序类用于缓存并检索配置项: ```java import com.google.common.collect.Maps; import org.springframework.core.io.support.PropertiesLoaderUtils; import java.io.IOException; import java.util.Map; import java.util.Properties; public class PropertiesUtil { private static final Map<String, String> cacheMap = Maps.newHashMap(); // 加载properties文件 static { try { Properties props = PropertiesLoaderUtils.loadAllProperties("application.properties"); for (String key : props.stringPropertyNames()) { cacheMap.put(key, props.getProperty(key)); } } catch (IOException e) { throw new RuntimeException(e); } } /** * 获取配置项值 */ public static String getProperty(String key){ return cacheMap.getOrDefault(key,"").trim(); } } ``` 此代码片段展示了如何利用 Guava 库中的 `Maps.newHashMap()` 方法初始化一个哈希映射表来保存键值对,并且使用 Spring 提供的 `PropertiesLoaderUtils` 来读取资源文件的内容。当第一次调用 `getConfig` 或者其他任何实例化该类的对象时会触发静态块执行一次性的加载操作。 #### 调用示例 假设已经在项目的 `src/main/resources/application.properties` 文件内定义了一些自定义设置,例如: ```properties app.title=Learning Spring Boot app.description=Working with properties file ``` 那么可以在任意位置像这样调用上述工具类以取得相应的值: ```java System.out.println(PropertiesUtil.getProperty("app.title")); // 输出: Learning Spring Boot System.out.println(PropertiesUtil.getProperty("app.description"));// 输出: Working with properties file ``` 这种方法允许开发者轻松地在整个应用程序的不同部分之间共享来自外部源的数据而无需每次都重新解析整个文件。不过需要注意的是,在多线程环境中应考虑同步问题以免发生并发修改异常;另外如果希望支持热更新,则可能需要更复杂的机制而不是简单的静态字段缓存方案。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JAVA·D·WangJing

您的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值