关于spring工厂的使用(ApplicationContext)

本文介绍了在SpringBoot开发中如何避免手动实现单例和工厂模式,而是利用Spring框架自身的功能。通过注解将实现类注入Spring容器,实现ApplicationContextAware接口并提供getBean方法,从而方便地获取和调用所需的服务。这种方法简化了代码,提高了代码的可维护性。

虽然工厂和单例是开发绕不开的话题,但是实际开发过程中,用到自己实现的单例和工厂的案例比较少,更多的是基于springboot框架的使用,而基于spring去使用工厂和单例,自然需要使用spring自己的工厂,而不是手动实现工厂和单例。

1.将多个基于同一接口实现的类,通过注解注入spring容器中;

2.实现ApplicationContextAware,并提供getBean方法;

3.通过getBean方法获取需要调用的实际实现。

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

/**
 *  @Description: 使用springboot的工厂,实现ApplicationContextAware
 */
@Component
public class SpringUtil implements ApplicationContextAware {

  private static ApplicationContext applicationContext;

  // 重写set方法
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    if(SpringUtil.applicationContext == null){
      SpringUtil.applicationContext = applicationContext;
    }
  }

  public static ApplicationContext getApplicationContext(){
    return applicationContext;
  }

  // 自定义getBean方法
  public static <T> T getBean(Class<T> clazz){
    return applicationContext.getBean(clazz);
  }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值