Netty 为handler注入服务接口

在Spring项目中,通常使用@Component和@Autowired进行bean管理与注入。然而,Netty的Handler不在Spring容器内,直接使用会导致注入失败。解决方案是创建一个SpringContextUtil工具类,实现ApplicationContextAware接口,静态获取ApplicationContext来手动获取所需bean。这样,在需要使用的地方,可以通过SpringContextUtil.getApplicationContext().getBean()方法获取bean,避免了直接注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:     

在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:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值