springboot中非Controller中@Autowired不起作用的问题

先说一下当时的场景
我用netty实现了udp服务端接收消息。但是接收到消息后我用springboot的异步执行但是@Autowired注入失败了。当时从网上找了很多资料一下代码是测试可用的

// 如果A类要注入B类那么需要在A类和B类类上添加注解@Component

@Component
public class A {
	@Autowired
	private B b; //有可能这样注入会失败 会有空指针异常
	//解决办法
	public static A a;
	@PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
	public void init() {
		a = this;
		a.b = this.b;
	}
	//用到了注入的方法
	public void hello(){
		a.b.he();//采用这种方式来写
	}
	
}

@Component
public class B {
	public void he(){
		System.out.println("测试代码");
	}
}

最后测试亲测可用

你可能感兴趣的:(java)