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

时间:2019-05-16 14:14:35

标签: java spring-boot singleton factory

具有需要从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;
    }
}

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

我试图通过几种方法来解决自动装配问题,但没有成功。

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

2 个答案:

答案 0 :(得分:1)

您可以将@Autowired与@Qualifier批注一起使用。让我们举一个例子,有一个接口,但是有多种实现。您要在不同的地方执行不同的操作。要了解更多信息,请参考此链接。 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
}

答案 1 :(得分:-1)

尝试一下。

@Component
public class StorageFactory {
    private static IApplicationProperties applicationProperties;

    @Autowired
    private StorageFactory(IApplicationProperties applicationProperties) {
        StorageFactory.applicationProperties = applicationProperties;
    }
}