I’m working on a project where the pre-existing code has lots of manually setup and wired together classes done in the main method – seems like a perfect example of something Spring is good at replacing. There are several objects that share a parent class, Widget. Each Widget contains a list of other widgets it depends on.
As an example, if you were to write this in code, it would something like:
class Widget{ void addDependency(Widget w}{..}}
class A extends Widget{...}
...
class G extends Widget{...}
A a = new A();
...
G g = new G();
a.addDependency(b);
b.addDependency(c);
b.addDependency(d);
b.addDependency(f);
c.addDependency(g);
You obviously can’t just have an @Autowired collection of Widgets, because then you’ll get a collection of all the Widgets. Is there a way for @Autowired to filter out so it only gets instances of certain subtypes?
There are two ways of doing this that I don’t like. The first would be to wire in all non-widget beans, and wire the Widget collections together after the context is loaded.The other way of doing this is by using @Resource to wire in the ApplicationContext and using a @PostConstructor to get what you need from the ApplicationContext. Both seem inelegant, is there another way?
I would probably do it similar to how @Matt is doing it but I might consider creating a custom BeanPostProcessor but Matt’s way I think is safer.
Then I would create a custom annotation:
I would put the annotation on each one of the widgets
Then you’ll do @Matt bean finding (you should checkout Spring’s BeanFactoryUtils) pulling out the dependecies from
bean.getClass().getAnnotation(Dependencies.class).Instead of the annotation you could do a property on the beans to list there deps.