Spring容器加载时执行自定义的方法

Spring容器加载时执行自定义的方法

需要实现的接口InitializingBean,ApplicationContextAware

案例

package com.djhu.research.web.service.impl.dataelement;

import com.djhu.research.web.bean.ResultResp;
import com.djhu.research.web.bean.TbDetaelementconfigVo;
import com.djhu.research.web.controller.entity.DataElementDto;
import com.djhu.research.web.controller.entity.DataElementInfo;
import com.djhu.research.web.service.IDataElementService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**

  • @Author zw

  • @DATE 2018/11/10 11:55

  • @VERSION 1.0.0
    **/
    @Service
    public class DataElementServiceImpl implements IDataElementService,InitializingBean,ApplicationContextAware {

    private ApplicationContext applicationContext;
    List dataElementServiceList = new ArrayList<>();
    //可以根据类型来确定具体执行那个类中的哪个方法!
    @Override
    public ResultResp querydataElementInfoDict(DataElementDto dataElementDto) {
    if(CollectionUtils.isNotEmpty(dataElementServiceList)){
    for (IDataElementService dataElementService:dataElementServiceList){
    ResultResp elementInfoDict = dataElementService.querydataElementInfoDict(dataElementDto);
    if (elementInfoDict != null){
    return elementInfoDict;
    }
    }
    }
    return defaultElementInfoDict;
    }

    /** {@inheritDoc} /
    @Override
    public void afterPropertiesSet() throws Exception {
    /
    *
    * new bean autowirebean 学习一下
    */
    JsonDataElementServiceImpl jsonDataElementService = new JsonDataElementServiceImpl();
    applicationContext.getAutowireCapableBeanFactory().autowireBean(jsonDataElementService);
    dataElementServiceList.add(jsonDataElementService);

     DataBaseDataElementServiceImpl dataBaseDataElementService = new DataBaseDataElementServiceImpl();
     applicationContext.getAutowireCapableBeanFactory().autowireBean(dataBaseDataElementService);
     dataElementServiceList.add(dataBaseDataElementService);
    

    }

    /** {@inheritDoc} */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
    }
    }

备注:IDataElementService 是DataBaseDataElementServiceImpl ,JsonDataElementServiceImpl ,DataElementServiceImpl 三个类的接口类!程序启动之后会把三个类的实例放入DataElementServiceImpl 类的属性dataElementServiceList 中!

发布了13 篇原创文章 · 获赞 3 · 访问量 2058

猜你喜欢

转载自blog.csdn.net/qq_33337186/article/details/94627621