Announcement Announcement Module
Collapse
No announcement yet.
retrieving a bean based on constructor args Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • retrieving a bean based on constructor args

    is there a way to directly access a bean based on the given constructor args?

    for instance:

    <bean id="foo" class="com.foo.bar.Baz">
    <constructor-arg index="0" value="alpha"/>
    </bean>
    <bean id="foo2" class="com.foo.bar.Baz">
    <constructor-arg index="0" value="beta"/>
    </bean>

    i'm looking for something like

    factory.getBeanByConstructorArg(0, "alpha")

    currently, the only thing that i could find close was
    BeanFactoryUtils.beansOfTypeIncludingAncestors

    but then i've still got to loop over them and do a get() until i find a match, which is just terrible for performance.

    thanks

  • #2
    What you describe is IMHO not supported by Spring. Anyway I fail to see the benefit in this approach. Why don't you just use a conditional lookup to "foo" or "foo2" respectively?
    You might argue that you have to ensure the bean has to exist, but also no one would hinder you to specify "gamma" as argument, for which no bean exists as well.

    But perhaps there are some more details to your use case I haven't considered?

    Regards,
    Andreas

    Comment


    • #3
      flexibility was the key here. looping over a collection of "beans of type" then calling "getCode()" until it matches isn't a very cost effective solution w/r/t time.
      The "code" which is indx=0 on the constructor doesn't always match the bean id, so clients were looking to simply "findByCode".

      Comment


      • #4
        How about a solution using a naming convention? Just name your beans after the code. E.g. Baz_alpha, Baz_beta.
        When looking up a "Baz" with argument "alpha" you can directly retrieve the bean "Baz_alpha".

        Regards,
        Andreas

        Comment

        Working...
        X