package com.ymdd.galaxy.comment.core.comment.service.impl;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import java.util.Map;
/**
*
* 獲取spring容器视哑,以訪問容器中定義的其他bean
* 類的名稱上增加@Component注解瘟栖,這樣spring初始化的時候才能把這個類納入到IOC容器,然后就可以在任意地方使用這個工具類了
* @author
*/
//一定要加注解Service或者Component监署,不然spring容器初始化的時候會通過注解來掃描,導(dǎo)致掃描不到
@Service
public class FmcSpringContext implements ApplicationContextAware {
private static ApplicationContext applicationContext;
//setApplicationContext方法就是把 ApplicationContext容器的值給你注入進(jìn)來舷夺,實例化后的值注入進(jìn)來旅挤,
//ApplicationContext容器:所有spring配置文件中的東西和注解自動注入的東西集合
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* 獲取applicationContext對象
*
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 根據(jù)bean的id來查找對象
*
* @param id
* @return
*/
public static Object getBeanById(String id) {
return applicationContext.getBean(id);
}
/**
* 根據(jù)bean的class來查找對象
*
* @param c
* @return
*/
public static <T> T getBeanByClass(Class c) {
Object obj = applicationContext.getBean(c);
if (obj != null) {
return (T) obj;
} else {
return null;
}
}
/**
* 根據(jù)bean的class來查找所有的對象(包括子類)
*
* @param c
* @return
*/
public static Map getBeansByClass(Class c) {
return applicationContext.getBeansOfType(c);
}
}
package com.ymdd.galaxy.comment.core.comment.service.impl;
import com.ymdd.galaxy.comment.core.comment.service.ICommentDetailService;
import com.ymdd.galaxy.comment.entity.comment.model.CommentDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class FmcInitContext {
@Autowired
FmcSpringContext springContextUtils;
private Map<Integer, ICommentDetailService> traceStrategys = new HashMap<>();
public ICommentDetailService buildTraceStrategy(Integer orderChanne) {
return traceStrategys.get(orderChanne);
}
@PostConstruct
public List<CommentDetail> initTraceStrategyMap() {
traceStrategys.put(23, springContextUtils.getBeanByClass(CommentDetailServiceImpl.class));
ICommentDetailService commentDetailService = springContextUtils.getBeanByClass(CommentDetailServiceImpl.class);
return commentDetailService.queryCommentListDayByCommentedTime();
}
}
@PostConstruct在所有注解類初始化完成之后會調(diào)用被它標(biāo)記的方法