Java 如何在Spring boot中创建简单的工厂设计模式?
具有需要从单例调用的StorageFactory.java类:Java 如何在Spring boot中创建简单的工厂设计模式?,java,spring-boot,singleton,factory,Java,Spring Boot,Singleton,Factory,具有需要从单例调用的StorageFactory.java类: @Component @Configuration @PropertySource("classpath:application.properties") public class StorageFactory { @Value("${storage.type}") private static String storageTypeString; @Autowired private IAppli
@Component
@Configuration
@PropertySource("classpath:application.properties")
public class StorageFactory {
@Value("${storage.type}")
private static String storageTypeString;
@Autowired
private IApplicationProperties applicationProperties;
@Autowired
private Environment env;
private static StorageType storageType;
public static IEntityStorage create() {
IEntityStorage storage = null;
storageType = applicationProperties.getStorageType();
switch (storageType){
case File:
storage = new FileStorageImpl();
break;
default:
throw new IllegalArgumentException("storage.type in application.properties is invalid.");
}
return storage;
}
public static StorageType getStorageType() {
return storageType;
}
}
来自单身汉的呼叫:
public final class DataManager {
private static StorageType storageType;
private static IEntityStorage storage;
private static DataManager instance = null;
protected DataManager() {
storage = StorageFactory.create(); <<<< Calling from here to create the factory
storage.init();
loadAll();
storageType = StorageFactory.getStorageType();
}
public static DataManager getInstance() {
if (instance == null){
synchronized (DataManager.class){
if (instance == null){
instance = new DataManager();
}
}
}
return instance;
}
}
公共最终类数据管理器{
私有静态存储类型StorageType;
私有静态存储;
私有静态DataManager实例=null;
受保护的数据管理器(){
storage=StorageFactory.create();您可以使用@Autowired和@Qualifier注释。让我们举一个例子,有一个接口,但有多个实现。您希望在不同的位置使用不同的实现。要了解更多信息,请参阅此链接
我提供了一个非常基本的方法供大家理解
@Component(value="bmw")
public BMW implements Vehicle {}
@Component(value="mercedes")
public Mercedes implements Vehicle {}
public class MyActualClass {
@Autowired @Qualifier("bmw")
private Vehicle vehicle;
... other code goes here
}
试试这个
@Component
public class StorageFactory {
private static IApplicationProperties applicationProperties;
@Autowired
private StorageFactory(IApplicationProperties applicationProperties) {
StorageFactory.applicationProperties = applicationProperties;
}
}
如果我理解正确,您希望使用Factory design使用不同类型的类?是的,但这里的问题是从Autowired ApplicationProperties.java获取属性,它告诉我要构建哪个类您正在自动连接一个接口,这是问题所在。请尝试从该接口自动连接一个实现。