我有一个问题,因为我移动到版本1.1.4.RELEASE的春天启动.
使用@Value注释的变量目前尚未填入值,尽管它们存在于application.properties中.在此之前,我使用的是Spring Boot @ version 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变量仍然为空.
解决方法
> @Value不适用于静态字段
> application.properties的属性可以自动使用,而不需要为其指定@PropertySource.
>而不是在main()方法中打印出属性,您应该在构建bean之后执行,例如使用@postconstruct
> application.properties的属性可以自动使用,而不需要为其指定@PropertySource.
>而不是在main()方法中打印出属性,您应该在构建bean之后执行,例如使用@postconstruct
充分的工作实例:
package demo;
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 javax.annotation.postconstruct;
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
@Value("${org.sample.sampleProperty}")
private String sampleProperty;
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
@postconstruct
public void postconstruct() {
System.out.print("SampleApplication started: " + sampleProperty);
}
}