Java springfactorybean,用于具有不同依赖关系的实现
假设我有一个存储bean,它包含与存储实体相关的逻辑Java springfactorybean,用于具有不同依赖关系的实现,java,spring,spring-ioc,Java,Spring,Spring Ioc,假设我有一个存储bean,它包含与存储实体相关的逻辑 public interface Storage { Object get(String id); String save(Object obj); } 我有3个实现: public FileStorage implements Storage { ... } // needs FileService public RedisStorage implements Storage { ... } // needs JedisPoo
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
根据这些属性,我必须创建一个bean,或者使用MixedStorage
创建两个bean(或者不创建,但这不在问题范围内)
我创建了一个StorageFactory bean:
public class StorageFactory {
// decide which impl to create basing on properties
}
现在,我正在传递所有实现所需的所有依赖资源(RedisSerializer
,RedisService
,FileService
)。在添加新的实现时,这些资源的数量可以增长得更快
有没有办法不传递所有依赖项,而是在以后初始化它们
我正在使用XML,我不知道它是否对您有用,但使用注释时,它看起来是这样的: 对于豆子:
@Component("FileStorage")
public FileStorage implements Storage { ... }
服务:
@Service
public class StorageFactory {
@Autowired
private Map<String,Storage> storageMap;//where key - bean name, value - class instance
}
@服务
公共级存储工厂{
@自动连线
私有映射storageMap;//其中key-bean名称,value-class实例
}
是的,映射将包含所有bean,但您将能够基于属性文件实现一些逻辑。是的,我正在考虑类似的事情:创建以属性为条件的bean(但在XML中看起来很难看),然后将列表注入工厂。在xml中,我们可以使用