Spring – Inject value into static variables

less than 1 minute read

Spring doesn’t allow to inject value into static variables, for example:

Wrong

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class GlobalValue {

  @Value("${mongodb.db}")
  public static String DATABASE;

}

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class GlobalValue {

    public static String DATABASE;

    @Value("${mongodb.db}")
    public void setDatabase(String db) {
        DATABASE = db;
    }

}

Categories:

Updated:

Leave a Comment