SpringBoot一般クラスでサービス、Daoなどの他のbeanを取得する方法

8514 ワード

回転:https://www.cnblogs.com/mrx520/p/7802831.html
ツールクラス
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 
     * @return
     */
    public static  T getBean(Class clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     *  name, Clazz Bean
     *
     * @param name
     * @param clazz
     * @param 
     * @return
     */
    public static  T getBean(String name, Class 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;
    }
}