0

I have created a Service to get bean by class name.

package com.ril.service.promise.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class BeanService {

    private static ApplicationContext applicationContextStatic;

    @Autowired
    BeanService(ApplicationContext applicationContext) {
        applicationContextStatic = applicationContext;
    }

    public static <T> T getBean(Class<T> className) {
        return applicationContextStatic.getBean(className);
    }
}

And I am initializing a static variable link this.

import java.time.LocalDateTime;
import java.util.*;

public class Mapper {

    private static Logger LOGGER = LoggerFactory.getLogger(Mapper.class);

    private static PEConfigService peConfigService = BeanService.getBean(PEConfigService.class);
} 

In mapper, as you see I am getting Bean in Mapper which is not spring bean class and setting it to a static variable.

The above code is working fine for me. But I want to know will it fine always?

1 Answers1

0

When you fire up a JVM and load a class for the first time (this is done by the class loader when the class is first referenced in any way) any static blocks or fields are 'loaded' into the JVM and become accessible. So in your case the Mapper class is not reference as part of spring initialization class hence the static variables defined is not yet loaded. You can find this reference link which could be helpful. How static Variables loaded at run time

srikanth r
  • 302
  • 3
  • 20