Spring认证-注入内部 Bean
发布于 3 年前 作者 yejuan 1817 次浏览 来自 分享

如您所知,Java 内部类是在其他类的范围内定义的,类似地,内部 bean是在另一个 bean 的范围内定义的 bean。因此,<property/> 或 <constructor-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>
例子
让我们使用 Eclipse IDE 并按照以下步骤创建一个 Spring 应用程序 -

脚步 描述
1 创建一个名为SpringExample的项目,并在创建的项目的src文件夹下创建一个包com.tutorialspoint。
2 使用添加外部 JAR选项添加所需的 Spring 库,如Spring Hello World 示例章节中所述。
3 创建Java类文本编辑,拼写检查和MainApp下com.tutorialspoint包。
4 在src文件夹下创建 Beans 配置文件Beans.xml。
5 最后一步是创建所有 Java 文件和 Bean 配置文件的内容并运行应用程序,如下所述。
这是TextEditor.java文件的内容-

package com.tutorialspoint;

public class TextEditor {
private SpellChecker spellChecker;

// a setter method to inject the dependency.
public void setSpellChecker(SpellChecker spellChecker) {
System.out.println(“Inside setSpellChecker.” );
this.spellChecker = spellChecker;
}

// a getter method to return spellChecker
public SpellChecker getSpellChecker() {
return spellChecker;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}
以下是另一个依赖类文件SpellChecker.java 的内容-

package com.tutorialspoint;

public class SpellChecker {
public SpellChecker(){
System.out.println(“Inside SpellChecker constructor.” );
}
public void checkSpelling(){
System.out.println(“Inside checkSpelling.” );
}
}
以下是MainApp.java文件的内容-

package com.tutorialspoint;

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

public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”);
TextEditor te = (TextEditor) context.getBean(“textEditor”);
te.spellCheck();
}
}
以下是配置文件Beans.xml,它具有基于 setter 的注入的配置,但使用内部 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”>

<!-- Definition for textEditor bean using inner bean -->
<bean id = “textEditor” class = “com.tutorialspoint.TextEditor”>
<property name = “spellChecker”>
<bean id = “spellChecker” class = “com.tutorialspoint.SpellChecker”/>
</property>
</bean>

</beans>
完成源文件和 bean 配置文件的创建后,让我们运行应用程序。如果您的应用程序一切正常,它将打印以下消息 -

Inside SpellChecker constructor.
Inside setSpellChecker.
Inside checkSpelling.

回到顶部