IOC操作Bean管理XML方式(有参构造注入属性)
生活随笔
收集整理的這篇文章主要介紹了
IOC操作Bean管理XML方式(有参构造注入属性)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
IOC操作Bean管理XML方式
目錄
有參構造注入屬性
(1)步驟(創建類,定義屬性,創建屬性對應的有參構造方法):
(2)步驟:在Spring 的xml配置文件中進行配置
(3)步驟:進行測試
結果:
有參構造注入屬性
?
(1)步驟(創建類,定義屬性,創建屬性對應的有參構造方法):
創建一個訂單類Orders:
Orders類內寫入屬性以及屬性的有參構造方法:
package com.lbj.spring5;/***訂單類* 使用有參構造注入屬性*/ public class Orders {//屬性private String oname;private String address;//有參構造方法public Orders(String oname, String address) {this.oname = oname;this.address = address;}//測試方法public void ordersTest(){System.out.println(oname+"::"+address);} }?
(2)步驟:在Spring 的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"><!--有參構造函數注入屬性--><!--配置Orders對象創建--><!--com.lbj.spring5.Orders寫完后會發現報錯,原因是默認找的是無參構造方法,但是Orders類里面的有參構造方法已經覆蓋無參構造方法--><bean id="orders" class="com.lbj.spring5.Orders"><!--但是當加入<constructor-arg>標簽后報錯就會消失,因為這里規定了是從有參構造方法里面找屬性--><constructor-arg name="oname" value="編程大神"></constructor-arg><constructor-arg name="address" value="北京"></constructor-arg></bean> </beans>也可以用索引的方式實現,效果一樣
<constructor-arg index="0" value="編程大神"></constructor-arg> <constructor-arg index="1" value="北京"></constructor-arg>?
?
(3)步驟:進行測試
package com.lbj.spring5.testdemo;import com.lbj.spring5.Orders; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;@Testpublic void testOrders(){//1.加載spring配置文件ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");//2.獲取配置創建的對象,通過context得到對象Orders orders=context.getBean("orders", Orders.class);//3.做輸出System.out.println(orders);//4.通過orders調用ordersTest方法orders.ordersTest();} }?
結果:
?
?
?
?
?
?
?
?
?
?
?
?
?
?
總結
以上是生活随笔為你收集整理的IOC操作Bean管理XML方式(有参构造注入属性)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c语言双链表排序交换节点_图解:单链表翻
- 下一篇: IOC操作Bean管理XML方式(外部属