-
Jul 31st, 2006, 07:39 PM
#1
Bean Access Pattern
I really don't like doing a context.getBean("bean") everytime I have to get a new Bean.
Plus that means I have to pass an Application Context around. Is there a better way to access Beans, like a DAO except for beans?
-
Aug 1st, 2006, 12:56 AM
#2
Well, what about wiring everything inside the context and then perform only one lookup at application start?
See here for more informations about IoC.
Regards,
Andreas
-
Aug 1st, 2006, 07:24 AM
#3
That doesn't work in my case. I have most of my things wired, but I have come to one can only be determined during runtime what type it should be.
-
Aug 1st, 2006, 07:30 AM
#4
If the possible types are fixed, maybe you can wire a factory bean (from the factory pattern, not necessarily a Spring FactoryBean) that allows you to choose the type to create based on runtime information.
Regards,
Andreas
-
Aug 1st, 2006, 07:58 AM
#5
Hi Quantam5
Indeed, using applicationContext.getBean("xxx") is a definite code smell. You may need to do it in a very small number of cases in some application scenarios, but these should (must!) be the exception to the rule.
The Spring reference documentation is a tad light on any discussion of the various ways to address this, but I'll elaborate some ideas right now; maybe other will pitch in and I'll be able to assemble a section for inclusion in the said reference documentation 
Andreas' second post on this thread is the most common way of addressing this issue (that is, of getting access to a bean that can only be determined at runtime). The creational patterns described in the seminal GoF book are patterns just because they are consistent recognisable idioms for creating objects. The Factory and Abstract factory patterns are great and I myself use them (where appropriate) in addition to using Spring IoC. I would second Andreas' suggestion of creating your own factory/service-locator interface and implementing it as a thin wrapper around Spring. This means that you will have a small dependency on the Spring IoC container, but that's ok because the dependency is only expressed in one place.
Another way of addressing this need is to use the ServiceLocatorFactoryBean. It's the Spring way of doing the above, with some small constraints in the signature of the methods you can define and use. I refer you to the Javadoc for said class, which is quite comprehensive (or at least I think it is - if you don't think that it is then let me know).
There are other options but none of them are as clean as the above two options, so unless prompted I will expound further on this topic. Let me know if this was helpful, or if you'd like an actual working example.
Cheers
Rick
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules