Announcement Announcement Module
Collapse
No announcement yet.
Constructing Beans Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Constructing Beans

    Hi, simple question from a newbie

    I can construct an empty basket like so:

    basket = (Basket)beanFactory.getBean("Basket");

    if it has dependencies that are set within the config file, they will be created by the spring container.

    However, what happens if i want to actually pass some other parameters to the constructor, like some things to add to the basket (which are only known at runtime)?

    Can I pass anything else in the call to the bean factory?

    Obviously, i can do
    basket = (Basket)beanFactory.getBean("Basket");
    basket.addItem(a);
    basket.addItem(b);

    but it doesn't seem as elegant.

    Also, maybe the basket doesn't have a parameterless constructor - maybe it always needs to be passed a reference to something else. In this case, how would we use spring to construct the item if we can't pass in a reference on the call to the bean factory?

    Many thanks!
    Craig

  • #2
    Originally posted by craigstreet View Post
    Also, maybe the basket doesn't have a parameterless constructor - maybe it always needs to be passed a reference to something else.
    You can use constructor injection - but you still have the problem of runtime arguments. It heavily depends on what you exactly want to inject. You can for example extract the runtime logic for retrieving the to-be-injected object into a factory and inject that one into the other bean.

    Joerg

    Comment


    • #3
      Have a look at this feature request. Maybe you might find it useful.

      It allows for runtime construction arguments while retaining Spring-based configuration. Note that it is required that the bean in question implements an interface.

      Regards,
      Andreas

      Comment

      Working...
      X