7.5.7: inject nested beans

Source: Internet
Author: User
Tags chop

If the bean on which a bean depends does not want to be directly accessed by the spring container, you can useNested Bean.<Bean.../>Elements are used to define nested beans. nested beans are only valid for external beans that are nested in them. Spring containers cannot directly access nested beans. Therefore, you do not need to specify the ID attribute when defining nested beans:

Axe. Java:

public interface Axe {public String chop();}

Person. Java:

public interface Person {public void useAxe();}

Chinese. Java:

public class Chinese implements Person{private Axe axe;public void setAxe(Axe axe) {this.axe = axe;}@Overridepublic void useAxe() {System.out.println(axe.chop());}}

Steelaxe. Java:

Public class steelaxe implements axe {@ overridepublic string chop () {return "cutting firewood well ";}}

Bean. XML Core Configuration:

<bean id="chinese" class="com.bean.Chinese">     <property name="axe">         <bean class="com.bean.SteelAxe"/>     </property></bean>

The preceding configuration ensures that the nested bean cannot be accessed by containers. Therefore, you do not need to worry about modifying the nested bean by other programs. The external bean usage is exactly the same as the previous usage.

Nested beans limit bean access and improve the cohesion of the program.

UseNested BeanAnd useRefThe reference of another bean in the container is essentially the same. In fact, to inject attributes to bean instances, when the attribute type is a composite type, a Java object needs to be passed in, so there are two ways:

① Use ref to reference the bean (Java object) configured in a container ).

② Use bean to temporarily configure a nested Bean (Java object ).

Test. Java:

Public class test {public static void main (string [] ARGs) {applicationcontext CTX = new classpathxmlapplicationcontext ("bean. XML "); person P = (person) CTX. getbean ("Chinese"); p. useaxe (); // cut firewood with a steel axe }}

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.