简体   繁体   中英

Inject value in a spring bean from constants java file

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";

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.

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM