Java – access all spring beans of a given type
I have a spring application (spring batch is not a web application) In the test class, I want to get access to all beans of a given type
Question 1) I can only get one bean at a time I can let my class implement beanfactoryaware to get a reference to beanfactory Then I can do beanfactory getBean(“name”); Access a single bean How do I get all the beans? I can traverse and delete those that don't belong to the class I want But somehow, I need a list of all the beans beanfactory knows or something else
Question 2) the bean I returned from beanfactory is a proxy If I try actors and use my bean, I'll get something like Java Lang.classcastexception: $proxy0 cannot be cast to org springframework. batch. item. database. JdbcCursorItemReader
Solution
You can use applicationcontextaware instead of beanfactoryaware to solve the first problem This passes ApplicationContext, which has a getbeansoftype () method that allows you to retrieve all beans of a given type
The second problem may be that something is creating an AOP proxy around your jdbcursoritemreader bean By default, these generated proxies will implement the same interface executed by jdbcursoritemreader (especially itemreader and itemstream) Your code should not try to convert to class type (jdbcursoritemreader), but to one of the interface types Usually, you can force the agent to directly extend the agent class, but I don't know your settings. I can't help you