在任意地方拿到SpringBoot管理的类(也称@Autowired拿到的值为空)

如果我们是在controller类中,要拿service中的方法,一般来说用@Autowired注解就可以

但是,如果想要在任意地方都要拿到service中的方法,使用@Autowired注解是不行的

可以写个工具类(之前在其他博客上看到的)

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

@Repository("beanUtil")
@Component

public class BeanUtil implements ApplicationContextAware  {
    protected static ApplicationContext applicationContext ;

    @Override
    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
        if (applicationContext == null) {
            applicationContext = arg0;
        }

    }
    public static Object getBean(String name) {
        //name表示其他要注入的注解name名
        return applicationContext.getBean(name);
    }

    /**
     * 拿到ApplicationContext对象实例后就可以手动获取Bean的注入实例对象
     */
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }
}

 

使用的话,大概是这样

        // 通过BeanUtil拿到FileStrategyService,自动装配拿不到
        FileStrategyService fileStrategyService = BeanUtil.getBean(FileStrategyService.class);
        FileStrategy fileStrategy = fileStrategyService.getFileStrategyById(strategyId);

 

posted @ 2022-04-22 15:33  袁骞骞  阅读(83)  评论(0编辑  收藏  举报