前言

Github:https://github.com/HealerJean

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

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

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

获取方式

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

工具类代码

package com.sankuai.windmill.interact.support.utils;

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 applicationContext = null;

    public SpringHelper() {
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringHelper.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class clazz) {
        return applicationContext.getBean((Class<T>) clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return  applicationContext.getBean(name, clazz);
    }

    public static Object getBeanByName(String beanName) throws BeansException {
        return applicationContext.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