前言

springboot 通常获取bean的方式

  1. 通过@Resource或者@Autowired 获取容器中的bean。
  2. 通过ApplicationContext 应用上下文获取

一、ApplicationContext获取bean

1.1 应用情景

为了保持代码规整、风格统一,我们通常对数据库对象entity和返回出参转换应用mapstruct来转换,不在业务内循环赋值,但通常有类似保存了用户id但出参要返回用户名称。

1.2 实现方式

重写mapstruct中的afterConvertTo方法赋值

/**
 * @author Mr.wanter
 * @time 2021-11-18 0018
 * @description
 */
@Mapper(componentModel = "spring")
public interface WarnMsgPageMapping extends BaseMapping<WarnMsgPO, WarningPageResp> {
    @Override
    default void afterConvertTo(WarnMsgPO a, WarningPageResp b) {
       b.setMsgTypeName(ObjNameUtil.getMsgTypeName(a.getMsgType()));
       b.setChannelStatus(ObjNameUtil.getChannelStatus(a.getId(),a.getStrategyChannels()));
       DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
       b.setPublishTime(ObjectUtils.isEmpty(a.getPublishTime())?"":dtf2.format(a.getPublishTime()));
       b.setCreateByName(ObjNameUtil.getUserName(a.getCreateBy()));
    }
}

获取bean工具

/**
 * @author Mr.wanter
 * @time 2021-10-26 0026
 * @description 获取bean,组件注入顺序靠后一点
 */

@Component
@Order(98)
public class SpringUtil implements ApplicationContextAware {

    private static Logger logger = LoggerFactory.getLogger(SpringUtil.class);
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringUtil.applicationContext == null) {
            SpringUtil.applicationContext = applicationContext;
        }
        logger.info("ApplicationContext配置成功,applicationContext对象:"+SpringUtil.applicationContext);
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    public static <T> T getBean(String name,Class<T> clazz) {
        return getApplicationContext().getBean(name,clazz);
    }
}

根据id获取各个数据名称的工具类

/**
 * @author Mr.wanter
 * @time 2021-11-15 0015
 * @description 根据id获取各个数据名称的工具类
 */
public class ObjNameUtil {

    private static EmsOrgDao orgDao;

    private static StrategyChannelDao strategyChannelDao;

    private static DicStrategyMsgTypeDao dicStrategyMsgTypeDao;

    private static DicStrategyDisTypeDao dicStrategyDisTypeDao;

    private static RedisClient redisClient;

    private static MaillistPersonDao maillistPersonDao;

    private static WarnChannelDao warnChannelDao;

    private static UserDao userDao;

    /**
     * 根据id获取行政区划名称
     *
     * @param id
     * @return
     */
    public static String getDistrictName(String id) {
        redisClient = SpringUtil.getBean(RedisClient.class);
        String name = redisClient.get(MonitorConstants.TABLE_FW_T_EMS_ORG_TREE_ALL + id);
        return ObjectUtils.isEmpty(name) ? "" : name;
    }

    /**
     * 根据id获取机构名称
     *
     * @param id
     * @return
     */
    public static String getOrgName(String id) {
        orgDao = SpringUtil.getBean(EmsOrgDao.class);
        EmsOrgPO po = orgDao.findByOrgCode(id);
        return ObjectUtils.isEmpty(po) ? "" : po.getOrgName();
    }

    /**
     * 根据id获取渠道名称
     *
     * @param channelId
     * @return
     */
    public static String getChannelName(String channelId) {
        strategyChannelDao = SpringUtil.getBean(StrategyChannelDao.class);
        StringBuffer sb = new StringBuffer();
        String[] split = channelId.split(",");
        if (split.length > 0) {
            for (int i = 0; i < split.length; i++) {
                Optional<StrategyChannelPO> byId = strategyChannelDao.findById(split[i]);
                if (byId.isPresent()) {
                    if (i == split.length - 1) {
                        sb.append(byId.get().getChannelName());
                    } else {
                        sb.append(byId.get().getChannelName() + ",");
                    }
                }
            }
        }
        return sb.toString();
    }

    /**
     * 根据id获取灾害类别
     *
     * @param id
     * @return
     */
    public static String getStrategyDisTypeName(String id) {
        dicStrategyDisTypeDao = SpringUtil.getBean(DicStrategyDisTypeDao.class);
        Optional<DicStrategyDisTypePO> byId = dicStrategyDisTypeDao.findById(id);
        return byId.isPresent() ? byId.get().getMsgType() : "";
    }

    /**
     * 根据id获取信息类型
     *
     * @param id
     * @return
     */
    public static String getMsgTypeName(String id) {
        dicStrategyMsgTypeDao = SpringUtil.getBean(DicStrategyMsgTypeDao.class);
        Optional<DicStrategyMsgTypePO> byId = dicStrategyMsgTypeDao.findById(id);
        return byId.isPresent() ? byId.get().getMsgType() : "";
    }

    /**
     * 根据id获取移动电话
     *
     * @param personIds
     * @return
     */
    public static  List<String> getPersonPhone(String personIds) {
        maillistPersonDao = SpringUtil.getBean(MaillistPersonDao.class);
        String[] split = personIds.split(",");
        List<String> personPhones=new ArrayList<>(split.length);
        if (split.length > 0) {
            for (int i = 0; i < split.length; i++) {
                Optional<MaillistPersonPO> byId = maillistPersonDao.findById(split[i]);
                if (byId.isPresent()) {
                    personPhones.add(byId.get().getTelNumber());
                }
            }
        }
        return personPhones;
    }

    /**
     * 根据用户id获取用户名
     * @param id
     * @return
     */
    public static String getUserName(String id) {
        userDao = SpringUtil.getBean(UserDao.class);
        Optional<UserPO> userPO = userDao.findById(id);
        return userPO.isPresent()?userPO.get().getName():"";
    }
}

在这里插入图片描述

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐