自定义web项目的初始化

概述

     启动一个项目时,大多数情况下我们都需要对项目进行一些自定义的初始化,如,加载数字字典,加载配置到redis等等,这需要我们在代码里进行业务实现.

基于xml配置

   使用场景:

         配置配在xml文件中,项目启动要读取这些配置才用这个方法.

   配置:

<!--初始化对象时,加载类中的init方法-->
<bean id="serviceHander" class="com.mlsama.springbootoracle.hander.ServiceHander" init-method="init">
    <!--给类属性赋值-->
    <property name="serviceNames">
        <map>
            <!--代收-->
            <entry key="86023040" value="weGet"/>
            <!--代付-->
            <entry key="86356041" value="wePay"/>
        </map>
    </property>
</bean>

类:

@Data
@Slf4j
public class ServiceHander{
    /**
     * 接口信息与对象,必须是静态的,否则再次调用时,map为null
     */
    private static Map<String, Map<String,Object>> serviceCache = new HashMap<>(16);

    /**
     * 配置在application-service.xml中的接口名称
     */
    private Map<String, String> serviceNames;

    /**
     * 1.实现ApplicationContextAware接口,获取applicationContext上下文对象
     * 进而获取bean对象
     * 2.@Autowired
     */
    @Autowired
    private ApplicationContext applicationContext;

    public static ServiceHander INSTANCE = new ServiceHander();

    private ServiceHander(){}

    /**
     * 初始化接口
     */
    public void init() {
        if (serviceNames != null){
            log.info("初始化的接口信息如下:");
            for (String procCode : serviceNames.keySet()){
                if (StringUtils.isNotBlank(serviceNames.get(procCode))){
                    List<String> methods = Arrays.asList(serviceNames.get(procCode).split(","));
                    log.info("{}:{}",procCode,methods);
                    Map<String,Object> map = new HashMap<>(16);
                    for (String method : methods){
                        map.put(method,applicationContext.getBean(procCode+"_"+method));
                    }
                    serviceCache.put(procCode,map);
                }
            }
        }else {
            throw new CommonSystemServiceException(ResultCodeConstant.RESPONSE_CODE_6601,"服务没有配置");
        }
    }
}

说明:

      加载bean ServiceHander时,先给属性serviceNames赋值,然后调用,类中的init方法进行初始化.

基于注解

   使用场景:

             项目启动,从数据库读取配置.

直接在方法上加 @PostConstruct即可,如下:

@PostConstruct
public void initConfig(){
    System.out.println("*****************从数据库获取配置******************");
}

实现接口InitializingBean

     使用场景:

             项目启动,从数据库读取配置.

@Slf4j
@Service("testHander")
public class TestHander implements InitializingBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("*****************从数据库获取配置******************");
    }
}

初始化bean时会调用afterPropertiesSet()方法,在这个方法中进行业务处理即可.

 这三种方法的加载优先级:

        实现接口InitializingBean > 基于注解@PostConstruct > 基于xml配置

    

猜你喜欢

转载自blog.csdn.net/mlsama/article/details/82662062