Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring@Value(“${}”)通常为空_Java_Spring_Spring Boot_Spring Bean_Spring Properties - Fatal编程技术网

Java Spring@Value(“${}”)通常为空

Java Spring@Value(“${}”)通常为空,java,spring,spring-boot,spring-bean,spring-properties,Java,Spring,Spring Boot,Spring Bean,Spring Properties,我正在使用Spring启动应用程序。在某些@组件类中,加载了@值字段,而在其他类中,这些字段始终为空 似乎在创建了我的@Bean/@Component之后加载了@Value 我需要从我的@Bean中的属性文件加载一些值 你有什么建议吗?你试过: @Component @PropertySource("file:/your/file/path") public class MyBean { private @Value("${property}") String property; ..

我正在使用Spring启动应用程序。在某些
@组件
类中,加载了
@值
字段,而在其他类中,这些字段始终为

似乎在创建了我的
@Bean
/
@Component
之后加载了
@Value

我需要从我的
@Bean
中的属性文件加载一些值

你有什么建议吗?

你试过:

@Component
@PropertySource("file:/your/file/path")
public class MyBean {

  private @Value("${property}") String property;
  ...
}
在构造bean(构造函数的执行)之后,注入属性(以及所有bean依赖项)

如果需要,可以使用构造函数注入

@Component
public class SomeBean {
    private String prop;
    @Autowired
    public SomeBean(@Value("${some.prop}") String prop) {
        this.prop = prop;
        //use it here
    }
}

另一个选项是移动带有
@PostConstruct
注释的方法中的构造函数逻辑,它将在创建bean并解析其所有依赖项和属性值后执行。

另一个可能的原因是“@Value”行位于需要这些属性/值的行下方


我花了很多时间调试这个问题,发现行的顺序很重要

将其解析为静态变量时,可能会发生这种情况。我曾经在某个时候观察到这一点,并通过消除静电来解决它。正如人们常说的,在使用静态时要小心。

使用@PropertySource(“classpath:application.properties”)我在启动时遇到了一个异常:没有找到符合依赖项要求的[org.springframework.core.io.Resource]类型的bean:至少需要1个符合此依赖项autowire候选项要求的bean。依赖项注释:{@javax.inject.inject()}。谢谢你用
@Component
注释了这个类吗?是的@叶甫盖尼已经将问题集中到了中心。我不能像现在这样在构造函数中使用用户值字段。是否将“其他类”注册为Springbeans?接收值的和不接收值的有什么区别?当然,它们是或Bean或组件。您正在检查构造函数中的值吗?谁将调用此构造函数?我正在尝试,但是没有调用这个“自定义”构造函数。您可能还有默认构造函数和自定义构造函数。删除没有参数的构造函数。我无法删除,因为删除默认构造函数时出现异常:找不到默认构造函数;嵌套的异常是java.lang.NoSuchMethodException:it.modem.ModemManager。()然后尝试使用@PostConstruct方法我还没有完成。它可以工作,但我不在构造函数中。那么在构造函数中不可能有值吗?