Reputation: 19
I have an application in which in a spring bean, value is being injected from a property file. I want to inject value from a constants.java file. What changes are do I need to make.
Spring bean
@Value("${resetPassword.email.key}")
private String resetPassword;
Property file
resetPassword.email.key = RESET_PASSWORD
Constants.java
public static final String resetPassword_email_key = "RESET_PASSWORD";
Upvotes: 0
Views: 2732
Reputation: 2490
You can inject value with @Value
from properties file or from spring bean.
To use properties file declare it with util:properties
tag:
<util:properties id="jdbcProperties" location="classpath:org/example/config/jdbc.properties"/>
And in spring bean do :
private @Value("#{jdbcProperties.url}") String jdbcUrl;
private @Value("#{jdbcProperties.username}") String username;
private @Value("#{jdbcProperties.password}") String password;
Or you can inject value of another spring bean like:
@Value("#{strategyBean.databaseKeyGenerator}")
public void setKeyGenerator(KeyGenerator kg) { … }
More info at http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/new-in-3.html
Upvotes: 0
Reputation: 37993
You can't reference java constant in properties file. And you don't need Spring injection for that. You simply do
private String resetPassword = Constants.resetPassword_email_key;
If you need to share Constants
class between multiple sub-projects (modules of a project), you may want to extract this class to a library that may be included into other projects.
Upvotes: 5
Reputation: 1500
You cannot inject a value to static properties. But you can assign to non-static setter as below:
@Component
public class GlobalValue {
public static String DATABASE;
@Value("${mongodb.db}")
public void setDatabase(String db) {
DATABASE = db;
}
}
From https://www.mkyong.com/spring/spring-inject-a-value-into-static-variables/
Upvotes: 0