当一个普通类想要调用service或其他spring管理的类的实例时

时间:2022-07-07 19:14:42
@Component
public class ServiceUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ServiceUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    /**
     *
     *
     * @param beanName service的名称
     * @return Object   service
     */
    public static Object getService(String beanName) {
        return applicationContext.getBean(beanName);
    }

}