gpt4 book ai didi

java - 注入(inject)静态属性值

转载 作者:行者123 更新时间:2023-12-02 03:33:00 24 4
gpt4 key购买 nike

我在使用 .properties 文件中的值时遇到一些问题。

我的 my-properties.properties 文件看起来像这样:

email.host=smtp.googlemail.com
email.port=465

然后我的配置文件如下所示:

@Configuration
@PropertySource("classpath:my-properties.properties")
class MyProperties{

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(){
return new PropertySourcesPlaceholderConfigurer();
}

}

然后我尝试在这个电子邮件类中使用它:

@Component("MyProperties.class")
public class AutomatedEmail {

private String recipient;
private String fullName;
private String tempPassword;

private Email email;

@Value("email.from")
private String from;

...

public AutomatedEmail(){
}
public AutomatedEmail(final String recipient, final String fullName, final String tempPassword) throws EmailException {
this.recipient = recipient;
this.fullName = fullName;
this.tempPassword = tempPassword;

}

但它总是返回说它为空。我还尝试了自动连线方法并在 MyProperties 类中设置整个电子邮件对象,但在我调用构造函数后该对象也为空

最佳答案

您需要用大括号和美元符号将属性文件中的名称括起来以创建 Spring 表达式。

@Value("${email.from}")

this tutorial on spring values中有更多信息

编辑:请注意,只有当 bean 已由 Spring 容器实例化和管理时,这才有效。如果您只调用 new Email();,您将无法将值注入(inject)到 Bean 中。

通读 bean IoC 上的 spring doco以获得更好的理解。关于 how to instantiate beans. 的更多信息

关于java - 注入(inject)静态属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37816045/

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