Reputation: 1888
I'm having some trouble using my values from a .properties
file.
My my-properties.properties
file looks something like this:
email.host=smtp.googlemail.com
email.port=465
Then my Configuration file looks like this:
@Configuration
@PropertySource("classpath:my-properties.properties")
class MyProperties{
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(){
return new PropertySourcesPlaceholderConfigurer();
}
}
And then I'm trying to use it in this Email class:
@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;
}
But it is always coming back saying its null. I've also tried an Autowired approach and setting up the entire email object in the MyProperties class, but that is null also after I call my Constructor
Upvotes: 0
Views: 446
Reputation: 2105
You need to surround the name in the properties file with curly brackets and a dollar sign to make a Spring expression.
@Value("${email.from}")
There's more info in this tutorial on spring values
Edit: Note that this will only work if the bean has been instantiated and managed by the Spring container. You won't be able to inject values into the bean if you just call new Email();
.
Read through the spring doco on bean IoC to get a better understanding. And a bit more info on how to instantiate beans.
Upvotes: 2