问题:
在Spring项目中我们总是习惯性的为要交给Spring托管的bean加上类注解@Component/@Service等,然后在使用其的地方使用@AutoWired/@Resource等注解注入实例.
然而Netty的handler是netty启动的时候new出来,并没有交给spring IOC托管,直接用@Component+@Autowired只能为 null:
方法:
可以写一个工具类,在任何需要获取Spring的javabean的地方,都可以通过此类获得.
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
*
* 获取spring容器,以访问容器中定义的其他bean
*/
@Component
public class SpringContextUtil implements ApplicationContextAware {
// Spring应用上下文环境
private static ApplicationContext applicationContext;
/**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境
*
* @param applicationContext
*/
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextUtil.applicationContext = applicationContext;
}
/**
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 通过name获取对象
*/
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
}
然后调用处不用注入实例,而是直接通过context获取该bean: