在Spring5.x中使用@PropertySource 是否需要使用Commons Configuration?

Is it necessary to use Commons Configuration to use @PropertySource in Spring 5.x?

我无法加载资源目录中的 属性 文件,

@Configuration
@PropertySource(value = "classpath:/test.properties", ignoreResourceNotFound = true)
public class ArgConfig {

    @Autowired
    private Environment env;

    @Value("${store.name}")
    private String name;

    public String getName() {
        return name;
    }

}

test.properties 包含 --> store.name=耐克

Property Source from Spring Documentation

按照文档中的相同方法仍然无法加载属性文件。

是否必须将其用作 test.properties?如果是这样,请使用 @PropertySource 注释。否则,像 application-test.properties 一样使用它并使用 @ActiveProfiles("test")

将配置文件设置为 test

另一种方法是,如果您想覆盖该值,请将 application.properties 放在 src/test/resources 下。

参考https://www.baeldung.com/spring-tests-override-properties了解更多信息

抱歉浪费了宝贵的时间。

我找到了答案,就是将 属性 文件放在资源目录下(我之前也这样做过,但不确定为什么会抛出错误)。

这是完整的代码, 项目结构:

@RestController
@RequestMapping("/")
public class SampleRestController {

    @Autowired
    private Store storeDetails;

    @GetMapping("/names")
    public List<String> getNames(){
        String storeName = storeDetails.getName();
        System.out.println("Store Name = " + storeName);
        return storeName!=null ? Arrays.asList(storeName) : Arrays.asList("store1","store2","store3");
    }
}

@Configuration
@PropertySource("classpath:/store.properties")
public class StoreConfig {
    @Autowired
    Environment env;

    @Bean
    public Store storeDetails() {
        Store store = new Store();
        store.setName(env.getProperty("store.name"));
        return store;
    }
}

@Component
public class Store {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

@SpringBootApplication
public class SpringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class);
    }

}

谢谢大家!!!