转: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 <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;
}
}