How to Assign Application Configuration of Spring to Static Fields

The Solution

  1. Using @Component inject the bean to the Spring IoC container.
  2. Using @Value read application configurations of Spring into non-static fields.
  3. Implements InitializingBean override afterPropertiesSet() method. Assigning non-static field values to static field values in afterPropertiesSet() method.

For example:

public class FileUploadUtils implements InitializingBean
    private static String endpoint;
    private static String accessKeyId;
    private static String accessKeySecret;
    private static String bucketName;
    private static OSSClient ossClient;

    private String getEndpoint;

    private String getAccessKeyId;

    private String getAccessKeySecret;

    private String getBucketName;

    public void afterPropertiesSet() throws Exception {
        endpoint = getEndpoint;
        accessKeyId = getAccessKeyId;
        accessKeySecret = getAccessKeySecret;
        bucketName = getBucketName;
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);