lundi 14 octobre 2019

Autowire list of subclasses of a class

I know it is possible to make a collection of some objects @Autowired, like

import org.aopalliance.intercept.Interceptor; // What's that? Nevermind.

@Component
public class A {
    @Autowired
    private List<Interceptor> magic;
}

// Example contents:
// org.springframework.cache.interceptor.CacheInterceptor
// org.springframework.transaction.interceptor.TransactionInterceptor

And it works just fine. Let's leave it aside how it manages to reach the type in generic bypassing erasure and focus on more applied matters.

Is it possible to make Spring inject some classes? Like

@Autowired
private List<Class> classes;
@Autowired
private List<Class<? extends MyHibernateEntity>> classes; // How deep can we reach for Spring to access these generics erased at runtime?..

Right now I use org.reflections from this answer, and it works quite flawlessly (at least for me).

But I want to learn something new and to reduce number of dependencies. (Spring itself is quite a big dependency, duh)

➥ So, is it possible to use some Spring's own classpath-parsing engine to get a list of subclasses of a class? Preferably one that was intended for public use.





Aucun commentaire:

Enregistrer un commentaire