通过枚举获取bean
/** * @Author: szc * @Description: 从枚举中获得容器bean * @Date: 2023/3/7 19:56 */ public enum GetBeanEnum2 { SERVICE_A("serviceA","服务A"){ // private ApplicationContext applicationContext; @Override public void setBean(ApplicationContext applicationContext) { // this.applicationContext = applicationContext; this.setBeanInterface(applicationContext.getBean(ServiceA.class)); } }, SERVICE_B("serviceB","服务b"){ // private ApplicationContext applicationContext; @Override public void setBean(ApplicationContext applicationContext) { // this.applicationContext = applicationContext; this.setBeanInterface(applicationContext.getBean(ServiceB.class)); } }; private String code; private String name; private GetBeanInterface beanInterface; GetBeanEnum2(String code, String name) { this.code = code; this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public GetBeanInterface getBeanInterface() { return beanInterface; } public void setBeanInterface(GetBeanInterface beanInterface) { this.beanInterface = beanInterface; } public static GetBeanEnum2 getBeanEnum(String code){ GetBeanEnum2[] values = GetBeanEnum2.values(); for (GetBeanEnum2 value : values) { if(value.getCode().equals(code)){ return value; } } return null; } //定义抽象方法 public abstract void setBean(ApplicationContext applicationContext); @Component @Slf4j public static class SetEnumService{ @Autowired private ApplicationContext applicationContext; @PostConstruct private void initService(){ GetBeanEnum2[] beanEnums = GetBeanEnum2.values(); for (GetBeanEnum2 beanEnum : beanEnums) { beanEnum.setBean(applicationContext); } } } }