spring如何使用xml裝配bean
更新時間:2019年11月28日 08:34:36 作者:綠色的草
這篇文章主要介紹了spring如何使用xml裝配bean,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
這篇文章主要介紹了spring如何使用xml裝配bean,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
使用XML裝配bean,在bean中調用另一個bean方法,首先建一個Dog類和一個Cat類
package soundsystem;
public class Dog {
private String Cry;//叫聲
//用setter方法注入
public void setCry(String cry) {
Cry = cry;
}
//定義一個狗叫方法
public void DogCry(){
System.out.println("狗叫:"+Cry);
Cat.CatCry();
catEat.CatEating();
}
}
package soundsystem;
public class Cat {
private String Cry;//叫聲
//用構造函數(shù)注入
public Cat(String cry){
this.Cry=cry;
}
//定義一個貓叫方法
public void CatCry(){
System.out.println("貓叫:"+Cry);
}
}
一個配置類Bean_DogXML.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.xsd">
<bean id="Dog" class="soundsystem.Dog">
<property name="Cry" value="汪汪汪~"></property>
<property name="Cat" ref="Cat"></property>
</bean>
<bean id="Cat" class="soundsystem.Cat">
<constructor-arg value="喵~"></constructor-arg>
</bean>
</beans>
現(xiàn)在開始測試
package Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import soundsystem.Cat;
import soundsystem.Dog;
@RunWith(SpringJUnit4ClassRunner.class)
public class Test {
@org.junit.Test
public static void main(String[] args) {
ApplicationContext ap=new ClassPathXmlApplicationContext("config/Bean_DogXML.xml");
Dog dog=(Dog)ap.getBean("Dog");
dog.DogCry();
}
}
輸出結果:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
淺析Java數(shù)據(jù)庫操作工具包jOOQ的使用
jOOQ?是一個輕量級的?Java?ORM(對象關系映射)框架,可用來構建復雜的?SQL?查詢,這篇文章主要來和大家介紹一下jOOQ的使用,需要的可以參考下2024-04-04
Java實現(xiàn)線程按序交替執(zhí)行的方法詳解
這篇文章主要為大家詳細介紹了Java如何實現(xiàn)線程按序交替執(zhí)行,文中的示例代碼講解詳細,對我們了解線程有一定幫助,需要的可以參考一下2022-10-10
springMVC之HandlerExceptionResolver使用
這篇文章主要介紹了springMVC之HandlerExceptionResolver使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11
SchedulingConfigurer實現(xiàn)動態(tài)定時,導致ApplicationRunner無效解決
這篇文章主要介紹了SchedulingConfigurer實現(xiàn)動態(tài)定時,導致ApplicationRunner無效的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05

