1. 程式人生 > >Spring Boot多模組工程如何載入application.properties

Spring Boot多模組工程如何載入application.properties

在一個pom.xml檔案中,包含多個模組,工程結構如下:

Parent-Project
|--MainApplication
|--Module1
|--ModuleN

在工程MainApplication中有main方法和註解SpringBootApplication。這個工程中application.properties 自動被載入的,所有我可以通過@Value來訪問相關的key。

@Value("${myapp.api-key}")
private String apiKey;

Within my Module1 I want to use a properties file as well (called module1.properties), where the modules configuration is stored. This File will only be accessed and used in the module. But I cannot get it loaded. I tried it with @Configuration and @PropertySource but no luck.

@Configuration
@PropertySource(value = "classpath:module1.properties")
public class ConfigClass {

How can I load a properties file with Spring-Boot and access the values easily? Could not find a valid solution.

My Configuration

@Configuration
@PropertySource(value = "classpath:tmdb.properties"
) public class TMDbConfig { @Value("${moviedb.tmdb.api-key}") private String apiKey; public String getApiKey() { return apiKey; } @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } }

Calling the Config

@Component
public class TMDbWarper {

@Autowired
private TMDbConfig tmdbConfig;

private TmdbApi tmdbApi;

public TMDbWarper(){
    tmdbApi = new TmdbApi(tmdbConfig.getApiKey());
}

I’m getting an NullPointerException in the constructor when I autowire the warper.