【发布时间】:2015-06-10 21:02:49
【问题描述】:
我有一种情况,我尝试使用 @Value 注释导致值为空。
这是一个大型项目的一部分,我不确定需要它的哪些部分。我正在使用 Java 注释(没有 xml 文件)和 Spring boot。
@Configuration
@EnableAutoConfiguration
@EnableConfigurationProperties
@ComponentScan
public class RESTApplication {
public static void main(String[] args) {
SpringApplication.run(RESTApplication.class, args);
}
}
application.properties 包含:
maxuploadfilesize=925000000
我确实尝试创建一个 PropertySourcesPlaceholderConfigurer,正如一些网站提到的那样。
@Configuration
public class AppConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
return new PropertySourcesPlaceholderConfigurer();
}
}
这是试图使用它的类:
@Component
public class MyClass {
@Value("${maxuploadfilesize}")
String maxFileUploadSize;
public String getMaxFileUploadSize() {
return maxFileUploadSize;
}
public void setMaxFileUploadSize(String maxFileUploadSize) {
this.maxFileUploadSize = maxFileUploadSize;
}
}
但是在运行时,maxFileUploadSize 始终为空。请注意下面的调试注释,其中 PropertySourcesPropertyResolver 似乎在 application.properties 文件中找到了正确的值。
2015-06-10 13:50:20.906 DEBUG 21108 --- [ main] o.s.c.e.PropertySourcesPropertyResolver : Searching for key 'maxuploadfilesize' in [applicationConfig: [classpath:/application.properties]]
2015-06-10 13:50:20.906 DEBUG 21108 --- [ main] o.s.c.e.PropertySourcesPropertyResolver : Found key 'maxuploadfilesize' in [applicationConfig: [classpath:/application.properties]] with type [String] and value '925000000'
【问题讨论】:
-
你能分享你检查 maxFileUploadSize 的代码吗?也不认为您应该需要 AppConfig。
-
它在调试器中为空,但我在 StringBuilder 中使用它来生成策略字符串。 StringBuffer policyStr = new StringBuffer(); policyStr.append(maxFileUploadSize);
-
我的意思是使用 MyClass bean 的代码。那个 bean 是在哪里注入的?
-
我删除了 AppConfig 并得到了相同的结果。更新 application.properties 文件会导致由 PropertySourcesPropertyResolver 在日志的 DEBUG 行中找到具有正确值的 maxFileUploadSize,但似乎没有发生 @Value 分配。
标签: spring-boot spring-annotations spring-properties