2

Imagine I have a Storage bean, which incapsulates logic, related to storing my entities.

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

And I have 3 implementations:

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

I also have 2 properties:

redis.enabled
file.enabled

Depending on these properties, I have to either create one of the beans, or both of them using MixedStorage (or none, but this is out of the question scope).

I have created a StorageFactory factory-bean:

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

Now I am passing all the dependent resources I need for all implementations (RedisSerializer, JedisPool, RedisService, FileService). Number of these resources can grow very faster, while adding new implementations.

Is there any way not to pass all the dependencies, but initialize them later?

I am using XML

Rahul
  • 1,727
  • 3
  • 18
  • 33

1 Answers1

0

I don't know if it be useful for you but using annotations it is look like this:

For beans:

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

For service:

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

And yes, the map will contains all beans but you will able to implement some logic based on your property file.

Slava Lubarskyi
  • 118
  • 1
  • 11
  • Yeah, I was thinking about something similiar: creating beans beinhg conditional on property (but it looks ugly in XML) and then injecting a list into the factory. In xml we can do the same autowire using `` – Rahul Oct 11 '18 at 14:51