1. 程式人生 > >netty下使用@autowired 無法注入問題

netty下使用@autowired 無法注入問題

handler下使用@autowired 無法注入可以使用ApplicationContextAware介面來getBean

package zfl.chat.utils;

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

import java.util.Locale;

/**
 * @Auther: ArimaKisho
 * @Date: 2018/12/3 17:46
 * @Description:
 */

@Component
public class SpringContextUtil implements ApplicationContextAware {
    /**
     * 獲取spring容器,以訪問容器中定義的其他bean
     */
    private static ApplicationContext context;
    /**
     * 實現ApplicationContextAware介面的回撥方法,設定上下文環境
     *
     * @param context
     */
    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException {
        SpringContextUtil.context = context;
    }

    /**
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return context;
    }
    /**
     * 獲取物件
     * 這裡重寫了bean方法,起主要作用
     * @param beanName
     * @return Object 一個以所給名字註冊的bean的例項
     * @throws BeansException
     */

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

    public static String getMessage(String key) {
        return context.getMessage(key, null, Locale.getDefault());
    }
}