Solve problems with singleton beans in spring that depend on prototype beans

Source: Internet
Author: User

When the spring bean is configured, a singleton bean may appear dependent on a prototype bean. Because singleton beans have only one chance of initialization, their dependency pages are only set at initialization time, and at this point they initialize a prototype bean. This will lead to the prototype Bean became singleton, this contradictory solution has two:

1. Discard the use of dependency injection and take the initiative to apply to the container when needed.

2. Using method injection

The first method is obviously unreasonable ~ ~ ~

Method injection typically uses the lookup method, which allows the spring container to override the abstract or concrete method of the bean in the container to return the bean.

Specific implementation methods:

The person is defined as Singleton, and the dependent address is defined as prototype


First define an abstract method in person, such as public abstract Address getaddress (); Of course, the name of this method can be customized, this method does not have to be implemented. The corresponding person of that class will also become abstract.

Configuration in Beans.xml:

Note: The bean default scope is singleton, so the configuration is omitted above.

<lookup-method>

Name: Specifies the method to be lookup, which is the custom method above

Bean: Associates The bean to be generated.

This has solved the contradiction of the dependence of different scope beans.

Solve problems with singleton beans in spring that depend on prototype beans

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.