spring-boot - @Value 始终为空

标签 spring-boot spring-annotations spring-properties

我遇到过一种情况,尝试使用 @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/

相关文章:

java - Spring如何保留@Controller生成的json中所有子实体的实体id?

java - 如何使用配置类中定义的方法?

java - 如何将环境变量中的 spring 属性设置为空值

java - Spring 属性查找/优先级如何工作?

java - @Scheduled注解Spring

java - 在 spring 中将 @Value 与条件一起使用,以便将值映射到字符串

spring-boot - 无法使用 Spring Cloud 连接 AWS SES

javascript - 客户端只接收一些服务器发送的事件

java - 类型/类是否需要用 @Component 或 @Service 注释才能用 @Value 注释其属性

java - Struts2 + Spring Security 2.06 : Valuestack is null when attempting to use @Secured on an Action method