有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring PropertySource多次拒绝扩展变量

我试图用以下方式创建一个spring配置类

@Configuration
@PropertySource(value={"file:${my.dir}/fileone.properties","file:${my.dir}/filetwo.properties"})
@Lazy(value=true)
public class SpringBeans {

    @Autowired
    Environment env;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
        return ppc;
    }

    @Bean.....
}

问题是变量${my.dir}被展开,以便找到fileone。属性,但它会立即抛出

java.io.FileNotFoundException: ${my.dir}/filetwo.properties (No such file or directory)

我使用的是spring 3.1.1。发布和发布Oracle JDK 7

这是实现中的缺陷/限制吗?有办法吗

我也找不到在注释中像在xml中那样设置ignore unsolvable=true的方法,这是默认情况下在注释中完成的吗


共 (1) 个答案

  1. # 1 楼答案

    您可以这样设置IgnoreUnsolvable:

    @Bean
    public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = PropertyLoadHelper.getPropertySourcesPlaceholderConfigurer();
        propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
        return propertySourcesPlaceholderConfigurer;
    
    }
    

    作为扩展价值的变通方法。。你可以尝试使用

    @Value(${my.dir})
    private String dir;
    

    然后在bean配置中使用它:

    propertySourcesPlaceholderConfigurer.setLocations(new ClassPathResource[]{
                    new ClassPathResource("config/"+dir+ "filename1" + ".properties"),
                    new ClassPathResource("config/"+dir+ "filename2" + ".properties")
            });