gpt4 book ai didi

java - 如何在Spring-boot中创建简单的Factory设计模式?

转载 作者:行者123 更新时间:2023-12-02 09:53:07 26 4
gpt4 key购买 nike

拥有需要从 Singleton 调用的 StorageFactory.java 类:

@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;
}
}

我想做的是使用Autowired ApplicationProperites.java(在StorageFactory .java内部)来获取我的属性(storageType)。

我尝试了多种方法来解决 Autowiring 问题,但没有成功。

在此阶段我该怎么做才能从属性文件中获取值?

最佳答案

您可以将@Autowired 与@Qualifier 注释一起使用。举个例子,有一个接口(interface),但有多个实现。你想在不同的地方有不同的实现。要了解更多信息,请参阅此链接。 https://www.mkyong.com/spring/spring-autowiring-qualifier-example/ .

我提供了一个非常基本的供您理解。

@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
}

关于java - 如何在Spring-boot中创建简单的Factory设计模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56170648/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com