2016-06-14 97 views
0

我在使用.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; 

} 

但它总是回来说它的空。我也尝试了一种Autowired方法,并在MyProperties类中设置了整个电子邮件对象,但在我致电我的构造函数后也为null。

回答

2

您需要在属性文件中用大括号和美元包围名称签署一个Spring表达式。

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

有一个在this tutorial on spring values

编辑的详细信息:请注意,如果在bean被实例化并且由Spring容器管理的,这只会工作。如果你打电话给new Email();,你将无法将值注入到bean中。

通读bean IoC的春天多可以更好地了解。并在how to instantiate beans.

+0

更多信息谢谢!我解决了这个问题,现在在'my-properties.properties'中显示了正在使用的值。但是,我仍然遇到问题,一旦我调用构造函数,值就为空。值是否在编译时被赋值,然后在创建我猜测的AutomatedEmail对象时被覆盖? – John

+1

啊,我明白你在做什么了!你需要通过Spring来管理bean。你不能使用'new'关键字来实例化它。我会更新我的答案。 – AndyN

+0

好的,谢谢!肯定有更多的阅读和重构要做! – John