gst*_*low 2 java configuration spring spring-boot
属性文件如下所示:
url1=path_to_binary1
url2=path_to_binary2
Run Code Online (Sandbox Code Playgroud)
根据这个我尝试以下方法:
@Component
@EnableConfigurationProperties
public class ApplicationProperties {
private Map<String, String> pathMapper;
//get and set
}
Run Code Online (Sandbox Code Playgroud)
在另一个组件中,我自动连接了ApplicationProperties:
@Autowired
private ApplicationProperties properties;
//inside some method:
properties.getPathMapper().get(appName);
Run Code Online (Sandbox Code Playgroud)
产生NullPointerException。
如何纠正?
我有正确的根据user7757360的建议:
@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="app")
public class ApplicationProperties {
Run Code Online (Sandbox Code Playgroud)
和属性文件:
app.url1=path_to_binary1
app.url2=path_to_binary2
Run Code Online (Sandbox Code Playgroud)
仍然不起作用
@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="app")
public class ApplicationProperties {
private Map<String, String> app;
Run Code Online (Sandbox Code Playgroud)
里面application.properties:
app.url1=path_to_binary1
app.url2=path_to_binary2
Run Code Online (Sandbox Code Playgroud)
仍然不起作用
如果您可以为属性文件提供更具体的示例,这将很有帮助。您应该在url1和url2中使用相同的前缀,然后才能使用
@ConfigurationProperties(prefix="my")
如
my.pathMapper.url1=path_to_binary1
my.pathMapper.url2=path_to_binary2
@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="my")
public class ApplicationProperties {
private Map<String, String> pathMapper;
//get and set for pathMapper are important
}
Run Code Online (Sandbox Code Playgroud)
NullPointerException大概是从空ApplicationProperties。
所有自定义属性都应该被注释@ConfigurationProperties(prefix="custom")。之后,在您的主类(具有 main 方法的类)上,您必须添加@EnableConfigurationProperties(CustomProperties.class). 对于自动完成,您可以使用:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
Run Code Online (Sandbox Code Playgroud)
如果不使用@ConfigurationProperties前缀,则仅使用字段名称。您属性中的字段名称。根据您的情况path-mapper,接下来您将具体说明key和value。例子:
path-mapper.key=value
Run Code Online (Sandbox Code Playgroud)
请记住,在更改您自己的属性后,您需要重新加载应用程序。例子:
https://github.com/kchrusciel/SpringPropertiesExample
| 归档时间: |
|
| 查看次数: |
13015 次 |
| 最近记录: |