多线程开发服务类引用注意事项

多线程开发服务类引用注意事项:

1.@Component注解的类,spring启动的时候会创建,引用的类(@Resource)会自动注入

@Component
public class ScheduleNetty {
    @Resource
    private NettyInfoCache nettyInfoCache;

 

2.程序运行中new的类中引用其他服务类

错误的类引用例子:

NettyClient nettyClient = new NettyClient();

public class NettyClient {
    @Resource
    private NettyInfoCache nettyInfoCache;
    
    ...
}

程序运行结果会是nettyInfoCache = null; 程序会报空指针异常:java.lang.NullPointerException: null
@Resource 注解的类会在程序启动运行的时候反射自动注入,而程序正常运行的时候创建的类中的@Resource引用的服务类不会反射自动注入。

 

正确的类引用例子:

NettyClient nettyClient = new NettyClient();

public class NettyClient {
    private NettyInfoCache nettyInfoCache = AppContextHelper.getBean("nettyInfoCache");
    
    ...
}

程序正常运行的时候创建的类,如果需要引用其他服务类,需要spring容器中获取bean对象

posted @ 2022-04-02 16:15  沉默的老牛  阅读(46)  评论(0编辑  收藏  举报