【问题标题】:using Spring property when initializing a class [duplicate]初始化类时使用Spring属性[重复]
【发布时间】:2018-11-21 14:52:09
【问题描述】:

以下产生空错误(“A”为空),但我不知道为什么。 bean是在属性值设置之前实例化的吗?

package org.ets.readtogether.queuing;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("Abean")
public class Test {

    @Value("${send.timeout.secs}")
    public Integer A;

    public int B = A * 1000;
}

【问题讨论】:

  • 嗯,没有对象怎么设置字段?
  • 也可以在@Value注解中使用SpEL:@Value("#{systemProperties['send.timeout.secs'] * 1000}")

标签: java spring


【解决方案1】:

试试这个:

@Component("Abean")
public class Test {

    @Value("${send.timeout.secs}")
    public Integer A;

    public int B;

    @PostConstruct
    public void init() {
       B = A * 1000;
    }
}

好例子here

【讨论】:

    【解决方案2】:

    Spring 在实例化对象后添加注入到对象中的所有依赖项。对象实例化在 Spring 完成的任何 @Autowired 依赖注入或 @Value 值分配之前。

    即使在 Spring 让对象注入依赖项之前,类对象的实例化也会失败,因为在对象实例化期间调用了语句 public int B = A * 1000;

    为了给变量B 赋值 Spring 完成所有注入后,请在@PostConstruct 方法或@AutoWired 构造函数中执行操作。

       public int B; // remove the assignment here.
    
       @PostConstruct
       public void postConstruct () {
           this.B = A * 1000;
       }
    

    上面的方法会在对象被实例化并且Spring完成它的工作之后被调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      • 2017-09-29
      • 2016-11-08
      • 1970-01-01
      相关资源
      最近更新 更多