Spring 使用@Autowired注解注入集合类List,Map替代ApplicationContextAware获取Bean

@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    /**
     * 上下文对象实例
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtil.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 
     * @return
     */
    public static  T getBean(Class clazz) {
        return getApplicationContext().getBean(clazz);
    }

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

日常采用模板方法设计模式时,我们一般根据业务场景或参数的不同,获取接口的不同实现类:

public interface BusinessService {
    public  void excute();
}


@Service(value = CarBusinessServiceImpl.SERVICE_NAME)
public class CarBusinessServiceImpl implements  BusinessService{

    public static final String SERVICE_NAME = "carBusinessServiceImpl";

    @Override
    public void excute() {
    }
}


@Service(value = BusBusinessServiceImpl.SERVICE_NAME)
public class BusBusinessServiceImpl implements BusinessService {

    public static final String SERVICE_NAME = "busBusinessServiceImpl";

    @Override
    public void excute() {
    }
}

获取 BusBusinessServiceImpl :

 BusinessService businessService = (BusinessService) ApplicationContextUtil.getBean(CarBusinessServiceImpl.SERVICE_NAME);

 

无差别执行实现类可以使用List

  @Autowired
  List list;
    

有差别执行实现类可以使用Map(这种场景比较常见);

  @Autowired
    Map map;
    
    public void test(){
        BusinessService businessService = (BusinessService) map.get(CarBusinessServiceImpl.SERVICE_NAME);

    }
 

 

  1. Spring在注入集合类的同时,会将集合泛型类的实例填入集合中,作为集合的初始值。
  2. 对于list、set填入的是注入类型Spring管理的实例,对于map,Spring会将service的名字作为key,对象作为value封装进入Map。

 

你可能感兴趣的:(开发小技巧)