虽然工厂和单例是开发绕不开的话题,但是实际开发过程中,用到自己实现的单例和工厂的案例比较少,更多的是基于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);
}
}

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

被折叠的 条评论
为什么被折叠?



