springboot中使用工厂方法(二)——使用枚举类管理工厂类bean名称

上讲我们总结了如何在springboot中优雅的使用工厂方法。

复制代码
//接口实现不变
public interface ReportService {
    String getResult();
}

//给实现类加上名字
@Component("A1")
public class ReportServiceA1 implements ReportService {
    @Override
    public String getResult() {
        return "我是A1";
    }
}

//给实现类加上名字
@Component("A2")
public class ReportServiceA2 implements ReportService {
    @Override
    public String getResult() {
        return "我是A2";
    }
}
复制代码

但是在@Component注解中使用字符串定义工厂Bean名称仍然不够优雅,字符串一旦写错,就容易操作程序错误。

加入能把枚举类变量作为Component的属性就好了,可惜Component只支持字符串类型的value

于是我想到能不能定义一个枚举类,用他的某个字符串类型的name来代替字符串硬编码,可惜失败了

在Component中始终无法将枚举变量的属性get出来,即便是public变量也不行。

只好变通一下,用下面的方法,在枚举中定义一个public类,其中定义好静态字符串变量,并建立枚举类和这些静态变量的关联关系。

复制代码
public enum SystemType {
    MYSQL(Name.MYSQL),
    ORACLE(Name.ORACLE),
    SQLSERVER(Name.SQLSERVER);
    
    private final String mpName;

    SystemType(String mpName) {
        this.mpName = mpName;
    }

    public String getMpName() {
        return mpName;
    }

    public class Name{
        public static final String MYSQL = "MP-mysql";
        public static final String ORACLE = "MP-oracle";
        public static final String SQLSERVER = "MP-sqlserver";
    }
}
复制代码

然后工厂bean就可以这样定义,这样就将工厂bean和一个枚举类锁定,更加好管理

复制代码
//接口实现不变
public interface ReportService {
    String getResult();
}

//给实现类加上名字
@Component(SystemType.Name.MYSQL)
public class ReportServiceA1 implements ReportService {
    @Override
    public String getResult() {
        return "我是A1";
    }
}

//给实现类加上名字
@Component(SystemType.Name.ORACLE)
public class ReportServiceA2 implements ReportService {
    @Override
    public String getResult() {
        return "我是A2";
    }
}
复制代码

 

posted @   Mars.wang  阅读(694)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
历史上的今天:
2022-02-01 java设计模式之享元模式
2022-02-01 java设计模式之装饰器模式
2022-02-01 java设计模式之组合模式
2022-02-01 java设计模式之适配器模式
2022-02-01 java设计模式之桥接模式
2022-02-01 java设计模式之工厂模式
2022-02-01 java设计模式之构建者模式
点击右上角即可分享
微信分享提示