SpringBoot普通类中如何获取其他bean例如Service、Dao(转)

工具类

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Author:Mr.X
 * Date:2017/11/8 10:00
 * Description:
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {

    /**
     * 上下文对象实例
     */
    private static ApplicationContext applicationContext;

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

    /**
     * 获取applicationContext
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 通过name获取 Bean.
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过class获取Bean.
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     *
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}

使用方法

public class ArticleFormConverter {

    private ArticleRepository articleRepository = (ArticleRepository) SpringContextUtils.getBean(ArticleRepository.class);

    public Article convert(ArticleForm articleForm) {
        // 更新
        if (articleForm.getId() != null) {
            Article article = articleRepository.findOne(articleForm.getId());
            BeanUtils.copyProperties(articleForm, article);
            article.setHtmlContent(Processor.process(article.getContent()));
            return article;
        }

        // 添加
        Article article = new Article();
        BeanUtils.copyProperties(articleForm, article);
        article.setHtmlContent(Processor.process(article.getContent()));
        // 添加时其他需要默认设置的属性值
        article.setReadSize(0);
        article.setStatus(ArticleStatus.UP_SHELVES.getCode());  // 默认为上架
        article.setCreateTime(new Date());
        article.setUserId(1); // TODO 暂定为,应该从session中取
        return article;
    }
}

参考链接

第三十二章:如何获取SpringBoot项目的applicationContext对象:http://www.jianshu.com/p/3cd2d4e73eb7

手动获取spring的ApplicationContext和bean对象:http://www.cnblogs.com/yangzhilong/p/3949332.html

转自https://www.cnblogs.com/mrx520/p/7802831.html

猜你喜欢

转载自www.cnblogs.com/shenyixin/p/9132452.html