工具类中采用静态注入的方式来注入bean

585 阅读1分钟

方式一

构造工具类

  1. 需要对工具类增加@Component 注解;
  2. @Autowired 注解注入bean;
  3. @PostConstruct 使用该注解定义init()方法,在方法中给当前对象赋值,@PostConstruct 注解的方法在加载类的构造函数之后执行,也就是在加载了构造函数之后,执行init方法;
@Component
public class CommonBeanUtil {

    private static CommonBeanUtil commonBeanUtil;
    
    @PostConstruct
    public void init() {
        commonBeanUtil = this;
    }
    
    @Autowired
    private SwitchConfig switchConfig;
 
    /***
     *
     *工具类的静态方法
     ***/
    public static String getSwitchValue(Sting key) {
        
          return commonUtils.switchConfig.getValue(key);
    }
    
}

使用

// 直接调用
CommonBeanUtil.getSwitchValue("1");

方式二

构造工具类

在Spring Boot可以扫描的包下

写的工具类为SpringUtil,实现ApplicationContextAware接口,并加入Component注解,让spring扫描到该bean

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

/**
 * 在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象
 **/
@Component
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

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

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

    /**
     * 通过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);
    }
    
}

使用

## 直接调用
SpringUtil.getBean(MyService.class)