spring8: di依赖注入--构造注入
生活随笔
收集整理的這篇文章主要介紹了
spring8: di依赖注入--构造注入
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?
package com.atChina.Test3;public class Student {private String name;private int age;private School school;public Student(){System.out.println("無(wú)參數(shù)構(gòu)造方法...");}public Student(String myName, int myAge, School mySchool){System.out.println("有參數(shù)構(gòu)造方法...");this.name = myName;this.age = myAge;this.school = mySchool;}public void setSchool(School school) {this.school = school;}public void setName(String name) {this.name = name;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Student [name=" + name + ", age=" + age + ", school=" + school+ "]";} }?
package com.atChina.Test3;public class School {private String address;private String name;public void setAddress(String address) {this.address = address;}@Overridepublic String toString() {return "School [address=" + address + ", name=" + name + "]";}public void setName(String name) {this.name = name;} } <?xml version="1.0" encoding="UTF-8"?> <!-- 引用Spring的多個(gè)Schema空間的格式定義文件 --> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!-- 構(gòu)造注入: spring調(diào)用類的有參數(shù)構(gòu)造方法,在構(gòu)造方法中給屬性賦值語(yǔ)法: 使用<constructor-arg>表示構(gòu)造方法的參數(shù).一個(gè)構(gòu)造方法的參數(shù)對(duì)應(yīng)一個(gè)<constructor-arg>標(biāo)簽--><!-- 構(gòu)造注入 --><bean id="student" class="com.atChina.Test3.Student"><!-- 構(gòu)造注入: 使用name屬性name:構(gòu)造方法的形參名value:簡(jiǎn)單類型參數(shù)的值ref:引用類型參數(shù)的值--><constructor-arg name="myName" value="林沖" /><constructor-arg name="myAge" value="23" /><constructor-arg name="mySchool" ref="xuexiao" /></bean><!-- 構(gòu)造注入, 使用index屬性--><bean id="student2" class="com.atChina.Test3.Student"><!-- 構(gòu)造注入: 使用index屬性index:表示構(gòu)造方法參數(shù)的位置,從0開(kāi)始value:簡(jiǎn)單類型參數(shù)的值ref:引用類型參數(shù)的值--><constructor-arg index="0" value="武松" /><constructor-arg index="2" ref="xuexiao" /><constructor-arg index="1" value="24" /></bean><!-- 構(gòu)造注入, 省略index屬性, 參數(shù)順序必須要與構(gòu)造器參數(shù)順序一致 --><bean id="student3" class="com.atChina.Test3.Student"><!-- 構(gòu)造注入: 使用index屬性index:表示構(gòu)造方法參數(shù)的位置,從0開(kāi)始value:簡(jiǎn)單類型參數(shù)的值ref:引用類型參數(shù)的值--><constructor-arg value="魯智深" /><constructor-arg value="25" /><constructor-arg ref="xuexiao" /></bean><bean id="xuexiao" class="com.atChina.Test3.School"><property name="name" value="武警大學(xué)"/><property name="address" value="陽(yáng)谷縣" /></bean> </beans>?
總結(jié)
以上是生活随笔為你收集整理的spring8: di依赖注入--构造注入的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: spring7: di依赖注入--设值注
- 下一篇: spring10: 引用类型的自动注入