20

我想在我的项目中使用类型安全配置(HOCON 配置文件),这有助于轻松和有组织的应用程序配置。目前我正在使用普通的 Java 属性文件(application.properties),这在大型项目中很难处理。

我的项目是 Spring MVC(不是 Spring Boot 项目)。有没有办法支持我的 Spring 环境(我被注入到我的服务中)由类型安全配置支持。这不应该破坏我现有的环境使用如@Value注释@Autowired Environment等。

我怎样才能以最少的努力和对代码的更改来做到这一点。

这是我目前的解决方案:寻找有没有其他更好的方法

@Configuration
public class PropertyLoader{
    private static Logger logger = LoggerFactory.getLogger(PropertyLoader.class);

    @Bean
    @Autowired
    public static PropertySourcesPlaceholderConfigurer properties(Environment env) {
        PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();

        Config conf = ConfigFactory.load();
        conf.resolve();
        TypesafePropertySource propertySource = new TypesafePropertySource("hoconSource", conf);

        ConfigurableEnvironment environment = (StandardEnvironment)env;
        MutablePropertySources propertySources = environment.getPropertySources();
        propertySources.addLast(propertySource);
        pspc.setPropertySources(propertySources);

        return pspc;
    }
}

class TypesafePropertySource extends PropertySource<Config>{
    public TypesafePropertySource(String name, Config source) {
        super(name, source);
    }

    @Override
    public Object getProperty(String name) {
        return this.getSource().getAnyRef(name);
    }
}
4

4 回答 4

15

我想我想出了一种比手动添加PropertySource到属性源更惯用的方法。创建一个PropertySourceFactory并引用它@PropertySource

首先,我们有一个TypesafeConfigPropertySource几乎和你一样的:

public class TypesafeConfigPropertySource extends PropertySource<Config> {
    public TypesafeConfigPropertySource(String name, Config source) {
        super(name, source);
    }

    @Override
    public Object getProperty(String path) {
        if (source.hasPath(path)) {
            return source.getAnyRef(path);
        }
        return null;
    }
}

接下来,我们创建一个返回该属性源的 PropertySource工厂

public class TypesafePropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        Config config = ConfigFactory.load(resource.getResource().getFilename()).resolve();

        String safeName = name == null ? "typeSafe" : name;
        return new TypesafeConfigPropertySource(safeName, config);
    }

}

最后,在我们的配置文件中,我们可以像其他任何方式一样引用属性源,PropertySource而不必自己添加 PropertySource:

@Configuration
@PropertySource(factory=TypesafePropertySourceFactory.class, value="someconfig.conf")
public class PropertyLoader {
    // Nothing needed here
}
于 2017-01-31T19:42:10.823 回答
5

您按如下方式创建一个 PropertySource 类,它与您的类相似,不同之处在于您必须返回值或 null 并且不让库抛出丢失的异常

public class TypesafeConfigPropertySource extends PropertySource<Config> {

    private static final Logger LOG = getLogger(TypesafeConfigPropertySource.class);

    public TypesafeConfigPropertySource(String name, Config source) {
        super(name, source);
    }

    @Override
    public Object getProperty(String name) {
        try {
            return source.getAnyRef(name);
        } catch (ConfigException.Missing missing) {
            LOG.trace("Property requested [{}] is not set", name);
            return null;
        }
    }
}

第二步是定义一个bean如下

    @Bean
    public TypesafeConfigPropertySource provideTypesafeConfigPropertySource(
        ConfigurableEnvironment env) {

        Config conf = ConfigFactory.load().resolve();
        TypesafeConfigPropertySource source = 
                          new TypesafeConfigPropertySource("typeSafe", conf);
        MutablePropertySources sources = env.getPropertySources();
        sources.addFirst(source); // Choose if you want it first or last
        return source;

    }

如果要将属性自动装配到其他 bean,则需要对@DependsOnpropertysource bean 使用注释以确保它首先被加载

希望能帮助到你

于 2017-01-20T12:05:09.140 回答
2

拉普利安德森回答了一些小的改进:

  • 如果找不到资源,则抛出异常
  • 忽略包含[:字符的路径

TypesafePropertySourceFactory.java

import java.io.IOException;

import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigParseOptions;
import com.typesafe.config.ConfigResolveOptions;

public class TypesafePropertySourceFactory implements PropertySourceFactory {

  @Override
  public PropertySource<?> createPropertySource(String name, EncodedResource resource)
      throws IOException {
    Config config = ConfigFactory
        .load(resource.getResource().getFilename(),
            ConfigParseOptions.defaults().setAllowMissing(false),
            ConfigResolveOptions.noSystem()).resolve();

    String safeName = name == null ? "typeSafe" : name;
    return new TypesafeConfigPropertySource(safeName, config);
  }
}

类型安全配置属性源.java

import org.springframework.core.env.PropertySource;

import com.typesafe.config.Config;

public class TypesafeConfigPropertySource extends PropertySource<Config> {
  public TypesafeConfigPropertySource(String name, Config source) {
    super(name, source);
  }

  @Override
  public Object getProperty(String path) {
    if (path.contains("["))
      return null;
    if (path.contains(":"))
      return null;
    if (source.hasPath(path)) {
      return source.getAnyRef(path);
    }
    return null;
  }
}
于 2018-05-24T15:46:56.403 回答
1

我尝试了以上所有方法并失败了。我遇到的一个特殊问题是 bean 的初始化顺序。例如,我们需要 flyway 支持来获取一些来自类型安全配置的覆盖属性,并且对于其他属性也是如此。

正如 m-deinum 对我们的评论之一所建议的那样,以下解决方案有效,也依赖于其他答案的输入。通过ApplicationContextInitializer在加载主应用程序时使用,我们确保道具在应用程序开始时加载并正确合并到“env”中:

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Import;

@SpringBootConfiguration
@Import({MyAppConfiguration.class})
public class MyApp {

    public static void main(String[] args) {
        new SpringApplicationBuilder(MyApp.class)
            .initializers(new MyAppContextInitializer())
            .run(args);
    }
}

ContextInitializer看起来像这样:

import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;

public class MyAppContextInitializer implements
    ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Override
    public void initialize(ConfigurableApplicationContext ac) {    
        PropertiesLoader loader = new PropertiesLoader(ac.getEnvironment());
        loader.addConfigToEnv();
    }

} 

PropertiesLoader像这样从配置加载属性并将其填充到环境中的工作:

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;

class PropertiesLoader {

    private ConfigurableEnvironment env;

    public PropertiesLoader(ConfigurableEnvironment env) {
        this.env = env;
    }

    public void addConfigToEnv() {
        MutablePropertySources sources = env.getPropertySources();

        Config finalConfig = ConfigFactory.load().resolve();
        // you can also do other stuff like: ConfigFactory.parseFile(), use Config.withFallback to merge configs, etc.
        TypesafeConfigPropertySource source = new TypesafeConfigPropertySource("typeSafe", finalConfig);

        sources.addFirst(source);
    }

}

我们还需要TypesafeConfigPropertySource适用于类型安全配置的:

import com.typesafe.config.Config;
import org.springframework.core.env.PropertySource;

public class TypesafeConfigPropertySource extends PropertySource<Config> {

    public TypesafeConfigPropertySource(String name, Config source) {
        super(name, source);
    }

    @Override
    public Object getProperty(String path) {
        if (path.contains("["))
            return null;
        if (path.contains(":"))
            return null;
        if (source.hasPath(path)) {
            return source.getAnyRef(path);
        }
        return null;
    }

}
于 2019-11-10T14:47:28.357 回答