springboot 在自定义注解中注入bean,解决注入bean为null的问题

问题:

在我们开发过程中总会遇到比如在某些场合中需要使用service或者mapper等读取数据库,或者某些自动注入bean失效的情况

解决方法:

1.在构造方法中通过工具类获取需要的bean

工具类代码:


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

/**
 * @author
 * @decription 通过工具类获取需要的的bean
 */
@Component
public class BeanContextUtils implements ApplicationContextAware {
    /**
     * 上下文对象实例
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BeanContextUtils.applicationContext = applicationContext;
    }

    /**
     * 获取applicationContext
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 通过name获取 Bean.
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过class获取Bean.
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     *
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

}

注入代码:

2.通过set方法注入bean

 private static SysDictFeignService service;

    @Autowired
    public void setSysDictFeignService(SysDictFeignService service){
        DictValidator.service = service;
    }

 3.通过有参构造方法传入

猜你喜欢

转载自blog.csdn.net/askuld/article/details/134777280