0

I've gotten the basics of Spring more or less down (I think) and I'm trying out new things. Currently, I'm trying to figure out a way not to have explicitly write a service class for each entity/repository if that service is just going to be extending a generic service class.

What I'd like to be able to do is, after the Entity and Repository beans are loaded, loop through them, check to see if a bean named [Model Name]Service exists and, if it does not, create a new instance of my generic service class, pass in the Repository object, and then register this service in the applicationContext.

Is this possible and if so, what is the best way to do it? I've been trying to figure out the PostProcessors, but the one that I think would actual work (BeanPostProcessor) doesn't seem like the appropriate place to do this.

Thanks for your time

nobeh
  • 9,784
  • 10
  • 49
  • 66
  • [WHYT?](http://mattgemmell.com/2008/12/08/what-have-you-tried/). Possible duplicates include [this](http://stackoverflow.com/q/2008175/248082) and [that](http://stackoverflow.com/questions/8711560/dynamic-creation-of-beans-in-spring). – nobeh Jun 17 '12 at 08:28
  • Right now, my approach is to create an ApplicationContextAware BeanPostProcessor, get the Repository beans with getBeansWithAnnotation(), loop through the keys to extract out the base name (i.e. remove Repository from the end of the bean name), call getBean(baseName + "Service) and, if the result is null, create a new instance of my generic service with the repository set, and then register and autowire that class with the baseName + "Service" name. I then return the original bean without modification. – Stephen Erdman Jun 17 '12 at 14:04
  • When looking for answers, I found things on dynamically creating beans, things on PostProcessors, and things on retrieving existing beans from the BeanFactory, but not on how they all go together. I think what I described above will probably work (I'm going to be trying it later today), but this seemed like something that a lot of people would want to do and my solution seems inappropriately hacky. So I was wondering if there was something obvious that I was missing. My question is is there an established/appropriate way to create dynamic beans based on ones already loaded? – Stephen Erdman Jun 17 '12 at 14:12
  • I see your points; that's why maybe it's really a good idea to describe your comments in your post, because it brings insight to the people who may want to answer and prevent others from judging (e.g. me) ;-) – nobeh Jun 17 '12 at 14:27

0 Answers0