gpt4 book ai didi

java - 加载构造函数时值为空

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:19:43 26 4
gpt4 key购买 nike

我看到 @Value 注释应该可以解决问题,而不是在构造函数中使用 Properties

它在我的另一个实现中工作,但在这里它不工作

Controller :

@Autowired
private Customer customer;

我的类(class)

@Service
public class Customer {

/** The soap GW endpoint. */
@Value("${soapGWEndpoint}")
private String soapGWEndpoint;

/** The soap GW app name. */
@Value("${soapGWApplName}")
private String soapGWAppName;

/** The soap GW user. */
@Value("${generic.user}")
private String soapGWUser;

/** The soap GW password. */
@Value("${generic.user.password}")
private String soapGWPassword;

public Customer () {
// All parameters are null:
login(soapGWEndpoint, soapGWAppName, soapGWUser, soapGWPassword);
}
}

但它们在 application.properties 文件中。

为什么在这种情况下我不能使用@Value?

最佳答案

在对象完全实例化之前,Spring 不会注入(inject)预属性的值(Spring 要做的第一件事就是调用您的构造函数,因为它是创建新对象的默认方式)。您应该在 @PostConstruct 方法中调用 login() 以便 Spring 在初始化对象后自动调用它:

@Service
public class Customer {

/** The soap GW endpoint. */
@Value("${soapGWEndpoint}")
private String soapGWEndpoint;

/** The soap GW app name. */
@Value("${soapGWApplName}")
private String soapGWAppName;

/** The soap GW user. */
@Value("${generic.user}")
private String soapGWUser;

/** The soap GW password. */
@Value("${generic.user.password}")
private String soapGWPassword;

public Customer () {
}

@PostConstruct
public void init() {
login(soapGWEndpoint, soapGWAppName, soapGWUser, soapGWPassword);
}
}

关于java - 加载构造函数时值为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54039484/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com