static静态方法获取yml配置文件里面的属性值

​ 我们经常会写util等类,里面的方法都是静态static的,

​ 这种情况下我们就没法像普通方法一样获取到yml的配置了,

​ 此时我们应该怎么获取呢?

1、在yml里面配置想要参数
user:
  name: dk
2、新建一个UserUtil来获取配置的名字
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
import javax.annotation.PostConstruct;
@Component
public class UserUtil {
 
    private static String userName;
 
    @Value("${user.name}")
    private String name;
 
    @PostConstruct
    public void getApiToken() {
        userName = this.name;
    }
 
    public static String getUserName() {
        // dk
        return userName;
    }
}
3、注意事项

首选要在util里建一个static的变量,然后使用@Value获取yml配置文件的值。

最后关键就是使用 @PostConstruct 熟悉将yml中配置的值赋给本地的变量,这样后面的静态方法就能使用了。

注意util类使用了 @Component 属性注解了说明是需要在启动类 Application 启动的时候加载的,

所以本地写一个方法调用 util 的时候是获取不到 name的。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐