问题由来:
在用netty写一个网络编程项目的时候,需要用到mongoTemplate这个springdata提供的mongodb的操作类。但是这个只能由springboot来注入,但是netty又会进行new操作,使得@Autowire无法正常工作。
解决方案:
1.我看网上的教程,有spring.xml来显式注入的,但这个有点麻烦。
2.还有几个教程没看懂 比如 http://blog.youkuaiyun.com/zhousenshan/article/details/75807999
3.我最后用的方式,在一层调用的时候使用静态方法static,当然static属性和方法是不能直接使用@Autowire注入的,这里用来一个@PostConstruct来进行操作。
就是在bean初始化时运行。
@Autowired
private PositionDao positionDao;
private static PositionDao positionDaoStatic;
@PostConstruct
public void init(){
positionDaoStatic=positionDao;
}
@PostConstruct 注解是在bean被构造时,先运行这个方法。
这样下面的static方法就可以使用@Autowire的属性了。而且调用静态方法也不需要new一个对象,或者使用springboot自动注入了。
另外,记得在类上加@Compact 注解。
ps:这个路子肯定是有点野的,等我研究清楚netty和spring框架可能会找到更好的方法。