標籤:return osi www. create auth size https repos shel
工具類
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: */@Componentpublic 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(轉)