1. 程式人生 > >SpringBoot普通類中如何獲取其他bean例如Service、Dao(轉)

SpringBoot普通類中如何獲取其他bean例如Service、Dao(轉)

@param todo spa .cn con elves IV exc date

工具類

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

SpringBoot普通類中如何獲取其他bean例如Service、Dao(轉)