Spring Boot始终显示@Value批注的值为空

时间:2019-05-29 11:16:45

标签: java spring-boot

我的Spring-Boot项目中有一个小类,其中从application.properties文件中获取了一些值。我的课程在src/main/java/com/company/package文件夹中,而我的应用程序属性文件在src/main/resources/application.properties中。这是我的课程:

@Component
@Configuration
@PropertySource("classpath:application.properties")
public class ElasticConnection {

private static final String INDEX = "index_name";
public static final String TYPE   = "type";

private String user;
private String password;

public ElasticConnection(@Value("${elasticsearch.user}")      String user,
                        @Value("${elasticsearch.password}") String password){
    this.user = user;
    this.password = password;
}

我正在将该类自动装配到Application类:

@Configuration
@SpringBootApplication
public class ElasticApplication {

@Autowired
ElasticConnection elastic;

public static void main(String[] args) {

    SpringApplication.run(ElasticApplication.class, args);
}

}

现在,一旦调用ElasticConnection类的构造函数,用户和密码就会设置为null。我知道可以正确读取值,因为InteliJ足以显示值(直到您单击@Value并再次显示“ $ {elasticsearch.user}”)

编辑:这是应用程序属性文件。

# App config
server.port=8070

 # Local ElasticSearch instance configuration
 elasticsearch.clustername = elasticsearch
 elasticsearch.host = localhost
 elasticsearch.port = 9300

 #spring.main.allow-bean-definition-overriding=true


 # Elasticsearch Settings
  elasticsearch.user=test
  elasticsearch.password=test

1 个答案:

答案 0 :(得分:0)

如果我们要对构造函数参数使用@Value批注,我们也不要忘记在构造函数上添加@Autowired批注。因此,您的代码应为:

@Component
@PropertySource("classpath:application.properties")
public class ElasticConnection {

private static final String INDEX = "index_name";
public static final String TYPE   = "type";

private String user;
private String password;

@Autowired
public ElasticConnection(@Value("${elasticsearch.user}")      String user,
                        @Value("${elasticsearch.password}") String password){
    this.user = user;
    this.password = password;
}

这使spring可以对字段使用构造函数注入。 除了通过构造函数注入值,您还可以在代码中尝试以下操作:

@Component
@PropertySource("classpath:application.properties")
public class ElasticConnection {

private static final String INDEX = "index_name";
public static final String TYPE   = "type";

@Value("${elasticsearch.user}") 
private String user;

@Value("${elasticsearch.password}") 
private String password;

//setters and getters
}

或者您甚至可以使用@ConfigurationProperties批注从属性文件中读取值。

相关:Spring @Autowire on Properties vs Constructor