【发布时间】:2014-07-25 07:34:46
【问题描述】:
自从我迁移到 Spring Boot 的 1.1.4.RELEASE 版本后,我遇到了一个问题。
我使用 @Value 注释的变量目前没有填充值,尽管它们存在于 application.properties 中。在此之前,我使用的是 Spring Boot @ 1.0.2 版,效果很好。
这一切都是从升级开始的,我没有更改任何代码。
SampleApplication.java
package org.sample;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
@ComponentScan
@EnableAutoConfiguration
@PropertySource(value = "classpath:application.properties")
public class SampleApplication {
private static Logger logger = LoggerFactory
.getLogger(TaskManagerApplication.class);
@Value("${org.sample.sampleProperty}")
private static String sampleProperty;
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
System.out.print("SampleApplication started: " + sampleProperty);
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
application.properties
spring.datasource.url: jdbc:mysql://127.0.0.1:3306/mydb
spring.datasource.username: root
spring.datasource.password: root
spring.datasource.driverClassName: com.mysql.jdbc.Driver
spring.jpa.show-sql: true
#Disable the ddl-auto:create once tables have been created
#spring.jpa.hibernate.ddl-auto: create
org.sample.sampleProperty=This is a sample property
photos.upload.dir=C:/temp/UserPhotos/
# Server port
server.port=8081
我已尝试添加 PropertySourcesPlaceholderConfigurer bean 甚至 PropertySourcesPlaceholderConfigurer,但问题仍然存在。
有人经历过吗?或者有没有一种新的方式来加载属性文件?
请注意,我的数据库连接和服务器端口正在被正确读取,因为我的应用程序可以连接到数据库并且我必须通过指定的端口访问它。 sampleProperty 变量仍然为空。
【问题讨论】:
-
为什么要声明
@PropertySource?这应该开箱即用(即没有@PropertySource和PropertySourcesPlaceholderConfigurerbean -
是的,我知道。我没有使用
@PropertySource和@PropertySourcesPlaceholderConfigurer。我在遇到这个问题后尝试了这些,但无济于事:( -
@Value(如`@Autowired)不适用于静态字段afaik。如果这在静态字段上有效,我会说那是无意的。 -
我尝试使用您提到的两个版本的 Spring Boot,但都不起作用。我没有工作是有道理的,因为您试图将值注入静态字段
-
在 1.1.5 和 1.1.6 中也有这个问题 - 有人知道这是否受支持吗? (即,这是错误还是功能?)
标签: java spring-mvc spring-boot