简体   繁体   中英

With Spring, how do I get a list of classes having a particular instance?

I have tried using BeanPostProcessor

@Override
    public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException
    {
        log.info("postProcessBeforeInitialization bean : " + beanName);
        if (bean instanceof TestAware)
        {
            testaware.add(((TestAware) bean).getClass());
            log.info("Added testAware bean : " + beanName);
        }
        return bean;
    }

But the problem, there are some classes which does not have bean definition. Is there any alternative or improved way to get . Thanks in advance.

Assuming you are asking how to find subtypes of TestAware

As suggested by it's name, BeanPostProcessor only "processes" spring managed beans, from the doc :

Factory hook that allows for custom modification of new bean instances

So you are using the wrong tool here. You probably should use some reflection to do what you want, for example, using Reflections :

// adapted from the home page sample
Reflections reflections = new Reflections("your.package");
Set<Class<? extends TestAware>> testAwares = reflections.getSubTypesOf(TestAware.class);

NB: the above sample code will give you subtypes, not instances of subtypes.

If you want to get all instances of a subtype in the application context then it is simple enough to look through them:

@Component
public class GetSubtypesOfClass implements ApplicationContextAware {

@Override
    public void setApplicationContext(ApplicationContext ac) throws BeansException {
        List<Subtype> matches = new ArrayList<>();
        for (String s : ac.getBeanDefinitionNames()) {
            Object bean = ac.getBean(s);
            if (Subtype.class.isAssignableFrom(bean.getClass())) {
                matches.add(bean);
            }
        }
    }
}

If however you are wondering why instances of your subtype aren't getting made available in the application context then you will need to load them explicitly in a context xml, or implicitly by classpath scanning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM