Search code examples
javaspringservice

How to initialize a variable in a Service class


I have a Spring Service class and I want to put a static variable in it that will be initialized with values once when the Service is created by Spring by Autowired.

I want to achieve something like this:

@Service
public class MyServiceImpl implements IService {

   public static HashMap<String,String> settings = new HashMap<String,String>();

   public MyServiceImpl() {
      settings.put("key1","value1");
      settings.put("key2","value2");
   }

And then when I Autowired that Service the variable will be initialized just once. Is there any solution how to achieve that?


Solution

  • You can use @PostConstruct:

    @PostConstruct
    private void init() {
        //fill values into map here
    }