Say I have this:
interface Something {
}
interface Fetcher {
}
class FetcherImpl implements Fetcher {
private final Class<?> klass;
public FetcherImpl(Class<?> klass) {
this.klass = klass;
}
public Something fetch() {
// Fetch an instance Something depending on the klass
}
}
class ClassA {
private final Fetcher fetcher;
public ClassA(Fetcher fetcher) {
this.fetcher = fetcher;
}
public void someMethod() {
// ...
Something something = fetcher.fetch();
// ...
}
}
class ClassB {
private final Fetcher fetcher;
public ClassB(Fetcher fetcher) {
this.fetcher = fetcher;
}
public void someMethod() {
// ...
Something something = fetcher.fetch();
// ...
}
}
So, the idea is:
- I have an data class,
Something
- I have a fetcher for that data class,
Fetcher
, that fetches it depending on the class. For example, it creates it depending on the contents of the file from the path/tmp/<class-name>.txt
- There are a lot of classes that are using (their respective instance of) the fetcher,
ClassA
andClassB
in the above example
Some important points:
- All clients of the fetcher are doing constructor injection, i.e. using a final field to store the fetcher. Thus bean post processors cannot be used
- The set of classes using the fetcher is an open one
- The creation of the fetcher instances should not be manually configured. I.e. when adding a class
ClassC
above that uses its own instance of the fetcher similar toClassA
andClassB
, there should not be additional Spring configuration for that particular class
Some real world examples of a similar pattern:
Loggers, e.g. instead of using
final Logger logger = LoggerFactory.getLogger(this.getClass())
the logger would be injected via the constructor
- Cache implementations (i.e. get a cache for a specific class)
- DAO objects (i.e. get a DAO for a particular bean, provided it can be generic enough)
Is this possible using Spring? If so, can you please provide some pointers or similar examples that I can read through? I am using Java configuration for Spring if that matters.