【发布时间】:2018-03-28 18:51:08
【问题描述】:
我在 Maven 中有一个 Spring-Boot-Application 作为多模块项目。结构如下:
Parent-Project
|--MainApplication
|--Module1
|--ModuleN
在MainApplication 项目中有main() 方法类用@SpringBootApplication 等注解。这个项目和往常一样有一个自动加载的 application.properties 文件。所以我可以使用@Value 注释访问这些值
@Value("${myapp.api-key}")
private String apiKey;
在我的 Module1 中,我还想使用一个属性文件(称为 module1.properties),其中存储了模块配置。该文件只能在模块中访问和使用。但我无法加载它。我用@Configuration 和@PropertySource 尝试过,但没有运气。
@Configuration
@PropertySource(value = "classpath:module1.properties")
public class ConfigClass {
如何使用 Spring-Boot 加载属性文件并轻松访问这些值?找不到有效的解决方案。
我的配置
@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();
}
}
调用配置
@Component
public class TMDbWarper {
@Autowired
private TMDbConfig tmdbConfig;
private TmdbApi tmdbApi;
public TMDbWarper(){
tmdbApi = new TmdbApi(tmdbConfig.getApiKey());
}
当我自动装配 warper 时,构造函数中出现 NullPointerException。
【问题讨论】:
-
你能关注这个帖子吗?它也有代码示例。 javacodegeeks.com/2016/11/…
-
属性文件是否复制到 jar 中?尝试解压缩您的 jar 并检查文件是否存在
-
好吧,没有更多信息,这只是一个疯狂的猜测,正如 JavaDoc 中所述:为了使用属性解析
定义或 @Value 注释中的 ${...} 占位符从 PropertySource,必须注册一个 PropertySourcesPlaceholderConfigurer。 -
我更新了我的帖子。在那里您可以看到配置以及我如何尝试访问该值。我解压缩了我的战争包。在战争中是我的模块的罐子,在模块罐子中是我的属性文件。
-
tmdbConfig 没有实例化?
标签: java spring spring-boot properties-file