Spring Boot 注入静态常量

2016/01/01 Java

Spring Boot 注入静态常量有两种方法。

使用 @Value

@Configuration
public class RabbitMqConfig {
    public static Boolean enable;
        @Value("${spring.rabbitmq.enable:false}")
    public void setEnable(Boolean enable) {
        RabbitMqConfig.enable = enable;
    }
}

注意 setEnable 一定不能使用 static 修饰。

继承 PropertySourcesPlaceholderConfigurer

/**
 * 暴露 spring 加载的 properties 配置
 */
public class PropertyPlaceholder extends PropertySourcesPlaceholderConfigurer implements InitializingBean {

    private static Map<String, String> propertyMap;

    public static String getProperty(String key) {
        return propertyMap.get(key);
    }

    public static Integer getInt(String key) {
        return Integer.valueOf(propertyMap.get(key));
    }

    public static Boolean getBool(String key) {
        return Boolean.valueOf(propertyMap.get(key));
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Properties result = super.mergeProperties();
        synchronized (PropertyPlaceholder.class) {
            if(propertyMap == null) {
                propertyMap = new HashMap<>();
                synchronized (PropertyPlaceholder.class) {
                    for (Object key : result.keySet()) {
                        String keyStr = key.toString();
                        String value = result.getProperty(keyStr);
                        propertyMap.put(keyStr, value);
                    }
                }
            }
        }
    }
}

Search

    Table of Contents