![](/img/trans.png)
[英]How to create a Simple Factory Pattern with autowired beans in Spring?
[英]How to create simple Factory design pattern in Spring-boot?
擁有需要從 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)。
我試圖通過幾種方法解決自動裝配問題,但沒有成功。
在這個階段我可以做什么才能從屬性文件中獲取值?
您可以將 @Autowired 與 @Qualifier 注釋一起使用。 讓我們舉個例子,只有一個接口,但有多種實現。 你想在不同的地方有不同的實現。 要了解更多信息,請參閱此鏈接。 https://www.mkyong.com/spring/spring-autowireing-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
}
DataManager
不由 Spring 管理,因此當您在構造函數中調用StorageFactory.create()
時,您應該在applicationProperties.getStorageType()
上看到 NullPointerException
在DataManager
上添加@Component
以便 spring 為您創建單例,而不是您單獨創建 DataManager 單例對象,然后在 DataManager 中自動裝配 StorageFactory
嘗試這個。
@Component
public class StorageFactory {
private static IApplicationProperties applicationProperties;
@Autowired
private StorageFactory(IApplicationProperties applicationProperties) {
StorageFactory.applicationProperties = applicationProperties;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.