使用spring,我在通过java阅读我的yaml时遇到了问题.让我先说明代码
@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "countries")
public class UserLimitReader {
private HashMap<String, Integer> orders;
private HashMap<String, Integer> requests;
public HashMap<String, Integer> getOrders() {
return orders;
}
public void setOrderRedeemableLimit(HashMap<String, Integer> orders)
{
this.orders= orders;
}
public HashMap<String, Integer> getRequests() {
return requests;
}
public void setMonthlyRedeemableLimit(HashMap<String, Integer> requests) {
this.requests= requests;
}
}
Run Code Online (Sandbox Code Playgroud)
我的yaml文件:
cassandra:
hosts: localhost:9142, 127.0.0.1:9142
keyspace: test
countries:
orders:
JPY: 1000
USD: 1000
requests:
JPY: 100000
USD: 100000
Run Code Online (Sandbox Code Playgroud)
spring context xml也有这个:
<bean id="yamlProperties"
class="org.springframework.beans.factory.config.YamlPropertiesFactoryBean">
<property name="resources">
<value>classpath:config/application.yaml</value> …Run Code Online (Sandbox Code Playgroud) 属性文件如下所示:
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)
仍然不起作用