前言

Github:https://github.com/HealerJean

博客:http://blog.healerjean.com

对于没有熟悉springBoot的小白来说,可能还在局限于spring上下文获取bean。其实SpringBoot也一样的

1、第一种通过工具类获取

获取方式

APIAdminUserService userService = SpringHelper.getBean(APIAdminUserService.class);

工具类代码

package com.hlj.netty.websocket.helper;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

/**
 * @Description
 * @Author HealerJean
 * @Date 2018/3/30  下午12:13.
 */
@Service
public class SpringHelper implements ApplicationContextAware {
    private static ApplicationContext context = null;

    public SpringHelper() {
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static <T> T getBean(Class clazz) throws BeansException {
        return context.getBean((Class<T>) clazz);
    }

    public static <T> T getBean(String clazz) throws BeansException {
        return (T) context.getBean(clazz);
    }

    public static Object getBeanByName(String beanName) throws BeansException {
        return context.getBean(beanName);
    }
}


2、直接通过注入获取

@Component
public class WebSocketServerInitializer extends ChannelInitializer {

    @Resource
    private ApplicationContext applicationContext;

    @Override
    protected void initChannel() throws Exception {
     pipeline.addLast(applicationContext.getBean(WebSocketFrameHandler.class));
    }
}

ContactAuthor