[译]13-spring 内部bean

spring基于xml配置元数据的方式下,位于property元素或者contructor-arg元素内的bean元素被称为内部bean,如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="outerBean" class="...">
      <property name="target">
         <bean id="innerBean" class="..."/>
      </property>
   </bean>

</beans>

上述xml配置文件中outerBean的依赖项target就是使用内部bean的方式进行注入的。但在实际应用中不推荐使用内部

bean,应为这种方式不利于代码的重用,一般使用ref属性进行引用.下面看一个例子:

1.创建包com.tutorialspoint.inner_bean,并在包中新建TextEditor.java和SpellChecker.java.内容分比如如下:

TextEditor.java

package com.tutorialspoint.inner_bean;

public class TextEditor {
    
    private SpellChecker spellChecker;

    public void setSpellChecker(SpellChecker spellChecker) {
        System.out.println("Inside setSpellChecker.");
        this.spellChecker = spellChecker;
    }

    public void spellCheck() {
        spellChecker.checkSpelling();
    }
}

SpellChecker.java

package com.tutorialspoint.inner_bean;

public class SpellChecker {
    
    public SpellChecker() {
        System.out.println("Inside SpellChecker constructor.");
    }

    public void checkSpelling() {
        System.out.println("Inside checkSpelling.");
    }

}

2.在src目录下新建inner_bean.xml配置文件,内容如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
   
   <!-- 下面示例了使用内部bean的方式注入spellChecker依赖项 -->
   <bean id="textEditor" class="com.tutorialspoint.inner_bean.TextEditor">
      <property name="spellChecker">
         <bean id="spellChecker" class="com.tutorialspoint.inner_bean.SpellChecker"/>
       </property>
   </bean>

</beans>

3.在com.tutorialspoint.inner_bean包新建MainApp.java.内容如下:

package com.tutorialspoint.inner_bean;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
    
   public static void main(String[] args) {
       
      ApplicationContext context = new ClassPathXmlApplicationContext("inner_bean.xml");

      TextEditor te = (TextEditor) context.getBean("textEditor");

      te.spellCheck();
   }
}

4.运行程序,检查结果:

原文地址:https://www.cnblogs.com/sysman/p/4481163.html