Whenever you create classes, they are not controlled by spring. Spring needs to instantiate classes so that it can inject its dependencies. This is, unless you use @Configurable and <context:load-time-weaver/> , but it's more of a hack, and I suggest against it.
Instead
- make a bean
prototype - get
ApplicationContext (in a web application this is done through WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext) ) - If the classes are not registered (and I assume that this is not the case), try casting to a
StaticApplicationContext (I'm not sure if this will work) and call registerPrototype(..) to register your classes in context. If this does not work, use GenericContext and registerBeanDefinition(..) - Get all instances matching your type using
appContext.getBeansOfType(yourclass) ; or if you just registered it and know its name - use only appContext.getBean(name) - Choose which one is applicable. Usually you will have only one entry in the
Map , so use it.
But I would generally avoid reflecting on Spring beans - there must be another way to achieve the goal.
Update: I just thought of an easier solution that would work if you don't need to register beans - that is, your dynamically generated classes will not be inserted into any other dynamically generated class:
And you will have your dependencies installed if your new class is not registered as a bean.
Bozho source share