我遇到过一种情况,尝试使用 @Value 注释会导致该值为 null。
这是一个大型项目的一部分,我不确定需要其中的哪些部分。我正在使用 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 始终为 null。请注意下面的调试注释,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'
最佳答案
看起来 MyClass 没有作为 SpringBean 进行处理,这意味着 @Value 注释没有被处理。
您可以通过提供默认值来检查这一点,例如 @Value("${maxuploadfilesize:'100'}")
。如果该值仍然为 null,那么您就知道 MyClass 没有实例化为 SpringBean。
由于它是用 @Component 注释的,因此您应该能够简单地注入(inject)它
@Autowired 私有(private) MyClass myclass;
关于spring-boot - @Value 始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30767248/