Spring Application Tutorial-2 method injection

Source: Internet
Author: User

We usually use the lookup method injection, which allows spring to replace the abstract or concrete method of a bean, returning the result of the other bean in the lookup container, which is usually a non-singleton bean.

The scope of a stateless bean can generally be configured as a singleton single instance, if we inject prototype BEANB into the beana of Singleton, and want to call Beana getbeanb () each time Can return a new BEANB, this requirement cannot be achieved using traditional injection methods . Because singleton beans inject The associated bean only once, although the scope of the BEANB is the prototype type, the returned object is not the bean that was injected the first time.

If you want to return a new BEANB each time you call Beana's GETBEANB (), an alternative is to have the bean implement the Beanfactoryaware interface, allowing Beana to access the container's references, and the following code can be implemented in a way that achieves the purpose:

[+]View Code

Public class bean_a implements beanfactoryaware{

Private bean_b bean_b= null; Private beanfactory beanfactory= null; @Override Public void setbeanfactory (beanfactory beanfactory) throws beansexception { This . beanfactory=beanfactory;     } Public bean_b getbean_b () { return beanfactory. Getbean ("Bean_b", Bean_b. class);     }} 

Spring Application Tutorial-2 method injection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.