spring loaded container to perform a method

onApplicationEvent is to complete the implementation of a method, I found here it is from the database with the names of cities coded code into customCodeAndName inside use. . .

import cn.txn.areamanage.AreaManageService;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
public class CustomCodeAndNameBeanPostProcessor implements ApplicationListener<ContextRefreshedEvent> {

    private static HashMap<String, String> customCodeAndName = null;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        synchronized (CustomCodeAndNameBeanPostProcessor.class) {

            if (event.getApplicationContext().getParent() != null) {
                return;
            }

            if (customCodeAndName != null) {
                return;
            }
            AreaManageService areaManageService = SpringContextUtil.getBean(AreaManageService.class);
            HashMap<String, String> stringStringHashMap = areaManageService.selectAllCodeName();
            this.customCodeAndName = stringStringHashMap;
        }
    }

    public static HashMap<String, String> getCustomCodeAndName() {
        return customCodeAndName;
    }

}

Because there are two containers using springmvc, this method will be performed twice, in order to determine performed only once by this:

  if (event.getApplicationContext().getParent() != null) {
                return;
            }

Guess you like

Origin blog.csdn.net/qq_38366063/article/details/93200659