具有需要从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;
}
}来自Singleton:的调用
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;
}
}我想要做的是使用自动头发的ApplicationProperites.java (inside StorageFactory .java)来获得我的财产(storageType)。
我试图解决自动装配的问题,几个接近,但它没有工作。
在此阶段,为了从属性文件中获取值,我可以做什么?
发布于 2019-05-16 14:20:31
您可以在@限定符注解中使用@Autowired。让我们举个例子,有一个接口,但有多个实现。您希望在不同的地方实现不同的实现。要了解这方面的更多信息,请参考此链接。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
}发布于 2022-07-07 23:06:43
DataManager不是由Spring管理的,因此当您在构造函数中调用StorageFactory.create()时,应该会看到applicationProperties.getStorageType()上的NullPointerException
在@Component上添加DataManager,这样spring就可以为您创建单例,而不是单独创建DataManager单例对象,然后在DataManager中自动创建StorageFactory
发布于 2019-05-16 15:25:58
尝尝这个。
@Component
public class StorageFactory {
private static IApplicationProperties applicationProperties;
@Autowired
private StorageFactory(IApplicationProperties applicationProperties) {
StorageFactory.applicationProperties = applicationProperties;
}
}https://stackoverflow.com/questions/56170648
复制相似问题