Spring-Boot多模块项目加载属性文件 [英] Spring-Boot multi module project load property-file
问题描述
我在Maven中有一个Spring-Boot-Application作为多模块项目.结构如下:
I have a Spring-Boot-Application as a multimodule-Project in maven. The structure is as follows:
Parent-Project
|--MainApplication
|--Module1
|--ModuleN
在MainApplication
项目中,存在用@SpringBootApplication
注释的main()
方法类,依此类推.与往常一样,该项目具有一个application.properties文件,该文件会自动加载.因此,我可以使用@Value
批注
In the MainApplication
project there is the main()
method class annotated with @SpringBootApplication
and so on. This project has, as always, an application.properties file which is loaded automatically. So I can access the values with the @Value
annotation
@Value("${myapp.api-key}")
private String apiKey;
在我的Module1中,我也想使用一个属性文件(称为module1.properties),用于存储模块配置.该文件只能在模块中访问和使用.但是我无法加载它.我用@Configuration
和@PropertySource
尝试了一下,但是没有运气.
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 {
如何使用Spring-Boot加载属性文件并轻松访问值?找不到有效的解决方案.
How can I load a properties file with Spring-Boot and access the values easily? Could not find a valid solution.
我的配置
@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());
}
自动连接整经器时,构造函数中出现NullPointerException.
I'm getting an NullPointerException in the constructor when I autowire the warper.
推荐答案
用于字段注入:
在构造任何bean之后,调用任何配置方法之前立即注入字段.这样的配置字段不必是公共的.请参考自动装配注释以获得完整用法.在这种情况下,请使用构造函数注入,如下所示:
Fields are injected right after construction of a bean, before any config methods are invoked. Such a config field does not have to be public. Refer Autowired annotation for complete usage. Use constructor injection in this case like below:
@Component
public class TMDbWarper {
private TMDbConfig tmdbConfig;
private TmdbApi tmdbApi;
@Autowired
public TMDbWarper(final TMDbConfig tmdbConfig){
this.tmdbConfig = tmdbConfig;
tmdbApi = new TmdbApi(tmdbConfig.getApiKey());
}
(或)
使用@PostConstruct
进行如下初始化:
@Component
public class TMDbWarper {
@Autowired
private TMDbConfig tmdbConfig;
private TmdbApi tmdbApi;
@PostConstruct
public void init() {
// any initialisation method
tmdbConfig.getConfig();
}
这篇关于Spring-Boot多模块项目加载属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!