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"; } }
浙公网安备 33010602011771号