SpringUtil工具类

2024-01-03 09:54:15
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

@Component
public class SpringUtil implements ApplicationContextAware {
 
    private static ApplicationContext applicationContext; // Spring应用上下文环境
 	
 	@Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    	SpringUtil.applicationContext = applicationContext;
    }
 
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
 
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        return (T) applicationContext.getBean(name);
    }
 
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<?> clz) throws BeansException {
        return (T) applicationContext.getBean(clz);
    }
}

文章来源:https://blog.csdn.net/userenoch/article/details/135345061
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。