在SpringBoot项目中,经常遇到如下场景:定义了属性配置类,比如XxxProperties类,如果将配置文件中的类注入到XxxProperties中,每次访问时都需要注入该配置类的实例化对象。那么,是否可以将XxxProperties中的属性设置为静态的,通过初始化之后,通过静态方法便可以直接访问?

通常使用方式

下面我们先来看看通常的使用方式:

@Data
@Component
@ConfigurationProperties(prefix = "remote")
public class ServerProperties {

    private String ip;

    private String port;
}

对应的yml配置文件如下:

remote:
  ip: 192.168.0.2
  port: 8080

此时如何使用呢?直接在需要使用的类中进行类的注入即可。

@Service
public class ConnectService {

    @Resource
    private ServerProperties serverProperties;

    public void connect(){
        String ip = serverProperties.getIp();
        String port = serverProperties.getPort();
        // ……
    }
}

上面的示例是通常的使用方法。但如果想直接使用ServerProperties.的形式来调用该如何注入呢?

静态属性注入

我们直接可以对ServerProperties的属性进行改造,这里新增一个URL的属性,对应的属性声明为静态的属性。

@Data
@Component
@ConfigurationProperties(prefix = "remote")
public class ServerProperties {

    private String ip;

    private String port;

    private static String url;

    public static String getUrl() {
        return ServerProperties.url;
    }

    public void setUrl(String url) {
        ServerProperties.url = url;
    }

}

同时呢,我们提供getter和setter方法。注意get方法是静态方法,这样初始化之后,我们就可以直接通过ServerProperties#getUrl来进行获取。而set方法内部需要通过ServerProperties.url 来进行赋值初始化。

经过上面的改造之后,当项目启动初始化完成之后,就可以直接通过ServerProperties#getUrl来获取静态值了。

当然这样是有需要注意的事项的,其中注入操作是通过setter方法进行注入的。所以必须提供这样的一个方法。如果使用@Value()进行注入,在该注解会放在setter方法上。

小问题

上面的方式虽然可以完美实现基于SpringBoot注入静态属性,但使用的时候还需要注意,由于属性是静态的了,因此变成了线程不安全的了。

通常,这种方式适合一次初始化,后续不再进行修改,直接获取使用即可。



SpringBoot中如何注入静态属性插图

关注公众号:程序新视界,一个让你软实力、硬技术同步提升的平台

除非注明,否则均为程序新视界原创文章,转载必须以链接形式标明本文链接

本文链接:https://www.choupangxia.com/2020/11/26/springboot-2/