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容器初始化的时候会通过注解来扫描,导致扫描不到
@Service
public class FmcSpringContext implements ApplicationContextAware {
private static ApplicationContext applicationContext;
//setApplicationContext方法就是把 ApplicationContext容器的值给你注入进来,实例化后的值注入进来,
//ApplicationContext容器:所有spring配置文件中的东西和注解自动注入的东西集合
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* 获取applicationContext对象
*
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 根据bean的id来查找对象
*
* @param id
* @return
*/
public static Object getBeanById(String id) {
return applicationContext.getBean(id);
}
/**
* 根据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;
}
}
/**
* 根据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在所有注解类初始化完成之后会调用被它标记的方法