- 获取上下文(使用@Component标注类,并implements ApplicationContextAware
@Component
public class ApplicationContextProvider implements ApplicationContextAware {
/**
* 上下文对象实例
*/
private static ApplicationContext applicationContext;
@SuppressWarnings("static-access")
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public ApplicationContextProvider() {
}
/**
* 获取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
* @return
*/
public static Object getBean(Class clazz) {
return getApplicationContext().getBean(clazz);
}
/**
* 通过name,以及Clazz返回指定的Bean
*
* @param name
* @param clazz
* @param
* @return
*/
public static Object getBean(String name, Class clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
- 在实现类上使用@Service(“XxxService”)指定sevice的名字,如下图:
@Service("XxxService")
@Transactional
public class XxxServiceImpl implements XxxService {
@Override
public Integer xxxXXX() {
...
}
}
- 工具类
/**
* @auth wujunquan
* 检查会员过期并做处理的定时器
* 2020-10-12
*/
public class MemberOverdueTimer extends TimerTask {
private XxxService xxxService;
public MemberOverdueTimer(ServletContext servletContext) {
super();
}
@Override
public void run() {
xxxService = (XxxService) ApplicationContextProvider.getBean("XxxService");
xxxService.xxxXXX();
}
}