當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring 注入内部 Beans
生活随笔
收集整理的這篇文章主要介紹了
Spring 注入内部 Beans
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
轉載自? ?Spring 注入內部 Beans
注入內部 Beans
正如你所知道的 Java 內部類是在其他類的范圍內被定義的,同理,inner beans?是在其他 bean 的范圍內定義的 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/beanshttp://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 | 使用?Add External JARs?選項,添加所需的 Spring 庫,解釋見?Spring Hello World Example?章節。 option as explained in the chapter. |
| 3 | 在?com.tutorialspoint?包中創建Java類TextEditor、SpellChecker?和?MainApp。 |
| 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 spellCheckerpublic 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();} }下面是使用內部 bean?為基于 setter 注入進行配置的配置文件?Beans.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/beanshttp://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.總結
以上是生活随笔為你收集整理的Spring 注入内部 Beans的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 吃鸡不卡的电脑配置(不卡的电脑配置)
- 下一篇: 电脑不卡的配置有哪些(电脑不卡的配置)