关于spring:Spring认证注入内部-Bean

8次阅读

共计 2400 个字符,预计需要花费 6 分钟才能阅读完成。

如您所知,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.or…d”>

<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.or…d”>

<!– 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.

正文完
 0