我正在尝试从application.properties
中读取一些属性。我创建了带有@Component
和@ConfigurationProperties
批注的配置类。
当我尝试从控制器类访问配置时,它的工作正常。但是,当我尝试从一个组件类访问配置时,它会抛出空指针异常。
以下是application.properties
和类。
application.properties
elasticsearch.ip=localhost
InputManagementController.java
@RestController
public class InputManagementController {
@Autowired
private Configuration configuration;
@GetMapping("/crawler/start")
public String start(){
try{
System.out.println(configuration.getIp()); ----> getting value localhost
ElasticsearchInterface es=new ElasticsearchInterface();
es.getInputs();
}catch (Exception e){
e.printStackTrace();
}
return "started";
}
}
ElasticsearchInterface.java
@Component
public class ElasticsearchInterface {
@Autowired
private Configuration configuration;
public List<Map<String, Object>> getInputs() {
System.out.println(configuration.getIp()); ---> getting java.lang.NullPointerException here
return null;
}
}
Configuration.java
@Component
@ConfigurationProperties("elasticsearch")
public class Configuration {
private String ip;
private int port;
private String cluster;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
}
答案 0 :(得分:2)
是src / main / resources。创建此文件夹以及此文件。假设您的情况是,将以下属性放在 application.properties 文件中;
myconfig.ip=192.168.166.42
myconfig.port=8090
为了读取属性文件,您需要一个带有@Configuration批注的类。对于需要阅读的所有属性,您需要带有@Value批注的适当字段。此外,您还需要这些带有@Value批注的字段的getter方法。请注意,将此类命名为“ Configuration”是一个非常糟糕的选择,因为还有一个具有相同名称的注释,因此我将其命名为“ AppConfig”
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Value("${myconfig.ip}")
private String ip;
@Value("${myconfig.port}")
private int port;
public String getIp() {
return ip;
}
public int getPort() {
return port;
}
}
然后,创建上面编写的此AppConfig类的字段,并使用@Autowired批注对其进行标记。然后,您可以轻松读取属性文件;
@RestController
@RequestMapping("/")
public class InputManagementController {
@Autowired
private AppConfig config;
@RequestMapping("/test")
public String test() {
return String.format(
"Configuration Parameters: Port: %s, Ip: %s",
config.getPort(),
config.getIp()
);
}
}
@RestController
public class InputManagementController {
@Autowired
private AppConfig configuration;
@Autowired
private ElasticSearchInterface elasticSearchInterface;
@GetMapping("/crawler/start")
public String start() {
try {
System.out.println(configuration.getIp());
es.getInputs();
} catch (Exception e) {
e.printStackTrace();
}
return "started";
}
}
@Component
public class ElasticSearchInterface {
@Autowired
private AppConfig configuration;
public List<Map<String, Object>> getInputs() {
System.out.println(configuration.getIp());
return null;
}
}
@Configuration
public class AppConfig {
@Value("${myconfig.ip}")
private String ip;
@Value("${myconfig.port}")
private int port;
public String getIp() {
return ip;
}
public int getPort() {
return port;
}
}