SpringContextUtil获取bean方法

说明:
非Spring环境获取Spring的Bean;所以使用SpringContextUtil来进行获取bean方法

新建SpringContextUtil

新建一个SpringContextUtil类,继承ApplicationContextAware;在类中申明Spring应用上下文

ApplicationContextAware :当一个类实现了该接口,将可以获取spring配置中所有的bean

代码如下:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

@Component
@Lazy(false)
public class SpringContextUtil implements ApplicationContextAware {
    private static final Logger logger = LoggerFactory.getLogger(SpringContextUtil.class);
    private static ApplicationContext applicationContext;

    public SpringContextUtil() {
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringContextUtil.applicationContext == null) {
            SpringContextUtil.applicationContext = applicationContext;
        }

        System.out.println("========ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象,applicationContext=" + SpringContextUtil.applicationContext + "========");
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    public static  T getBean(Class clazz) {
        return getApplicationContext().getBean(clazz);
    }

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

获取类如下:

AaaaServiceImpl aaaaService  = SpringContextUtil.getApplicationContext().getBean(AaaaServiceImpl.class);

你可能感兴趣的:(#,JAVA使用,java,spring,开发语言)