【问题标题】:Spring factory bean for implementations with different dependencies用于具有不同依赖项的实现的 Spring 工厂 bean
【发布时间】:2018-10-11 13:25:14
【问题描述】:

假设我有一个 Storage bean,它封装了与存储我的实体相关的逻辑。

public interface Storage {
   Object get(String id);
   String save(Object obj);
}

我有 3 个实现:

public FileStorage implements Storage { ... } // needs FileService
public RedisStorage implements Storage { ... } // needs JedisPool, RedisService and RedisSerializer
public MixedStorage implements Storage { ... } // combines other Storages

我还有两个属性:

redis.enabled
file.enabled

根据这些属性,我必须使用MixedStorage 创建一个bean,或者同时创建两个bean(或没有,但这不在问题范围内)。

我创建了一个 StorageFactory factory-bean:

public class StorageFactory {
   // decide which impl to create basing on properties
}

现在我正在传递所有实现所需的所有依赖资源(RedisSerializerJedisPoolRedisServiceFileService)。这些资源的数量可以增长得更快,同时添加新的实现。

有什么办法不把所有的依赖都传过去,以后再初始化?

我正在使用 XML

【问题讨论】:

    标签: java spring spring-ioc


    【解决方案1】:

    我不知道它是否对你有用,但使用注释它看起来像这样:

    对于豆类:

    @Component("FileStorage")
    public FileStorage implements Storage { ... }
    

    服务:

    @Service
    public class StorageFactory {
       @Autowired
       private Map<String,Storage> storageMap;//where key - bean name, value - class instance
    }
    

    是的,地图将包含所有 bean,但您将能够根据您的属性文件实现一些逻辑。

    【讨论】:

    • 是的,我在考虑类似的事情:创建以属性为条件的 bean(但在 XML 中看起来很难看),然后将列表注入工厂。在 xml 中,我们可以使用 &lt;bean ... autowire="byType" .. /&gt; 进行相同的自动装配
    猜你喜欢
    • 2015-08-25
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多