在非Spring类中获取Spring管理的对象

在非Spring类中获取Spring管理的对象

工具类:

package com.xxx.task.util;

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

@Component
public class MyBeanUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }

    public static <T> T getBean(Class<T> beanClass) {
        if (applicationContext == null) {
            throw new IllegalStateException("Application context has not been set");
        }
        return applicationContext.getBean(beanClass);
    }

    public static <T> T getBean(String beanName) {
        if (applicationContext == null) {
            throw new IllegalStateException("Application context has not been set");
        }
        return (T) applicationContext.getBean(beanName);
    }
}

使用:

ZipConfig zipConfig = MyBeanUtil.getBean(ZipConfig.class);
posted @ 2023-08-01 15:26  张瑞丰  阅读(58)  评论(0编辑  收藏  举报