SpringBeanUtil获取Spring Bean

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @ClassName: SpringBeanUtil
 * @Description: (spring功能类 , 用于获取bean)
 */
@Component
//@Order(Integer.MIN_VALUE)
public class SpringBeanUtil implements ApplicationContextAware {

    protected final static Log logger = LogFactory.getLog(SpringBeanUtil.class);

    private static ApplicationContext ctx = null;

    public void setApplicationContext(ApplicationContext ctx) throws BeansException {

        SpringBeanUtil.ctx = ctx;
    }

    public static ApplicationContext getApplicationContext() {

        return ctx;
    }

    public static <T> T getBean(String prop) {

        Object obj = ctx.getBean(prop);
        if (logger.isDebugEnabled()) {
            logger.debug("property=[" + prop + "],object=[" + obj + "]");
        }
        return (T) obj;
    }
}

posted @ 2022-04-13 11:13  倔强的老铁  阅读(401)  评论(0编辑  收藏  举报