spring8: di依赖注入--构造注入
生活随笔
收集整理的這篇文章主要介紹了
spring8: di依赖注入--构造注入
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
package com.atChina.Test3;public class Student {private String name;private int age;private School school;public Student(){System.out.println("無參數構造方法...");}public Student(String myName, int myAge, School mySchool){System.out.println("有參數構造方法...");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的多個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"><!-- 構造注入: spring調用類的有參數構造方法,在構造方法中給屬性賦值語法: 使用<constructor-arg>表示構造方法的參數.一個構造方法的參數對應一個<constructor-arg>標簽--><!-- 構造注入 --><bean id="student" class="com.atChina.Test3.Student"><!-- 構造注入: 使用name屬性name:構造方法的形參名value:簡單類型參數的值ref:引用類型參數的值--><constructor-arg name="myName" value="林沖" /><constructor-arg name="myAge" value="23" /><constructor-arg name="mySchool" ref="xuexiao" /></bean><!-- 構造注入, 使用index屬性--><bean id="student2" class="com.atChina.Test3.Student"><!-- 構造注入: 使用index屬性index:表示構造方法參數的位置,從0開始value:簡單類型參數的值ref:引用類型參數的值--><constructor-arg index="0" value="武松" /><constructor-arg index="2" ref="xuexiao" /><constructor-arg index="1" value="24" /></bean><!-- 構造注入, 省略index屬性, 參數順序必須要與構造器參數順序一致 --><bean id="student3" class="com.atChina.Test3.Student"><!-- 構造注入: 使用index屬性index:表示構造方法參數的位置,從0開始value:簡單類型參數的值ref:引用類型參數的值--><constructor-arg value="魯智深" /><constructor-arg value="25" /><constructor-arg ref="xuexiao" /></bean><bean id="xuexiao" class="com.atChina.Test3.School"><property name="name" value="武警大學"/><property name="address" value="陽谷縣" /></bean> </beans>?
總結
以上是生活随笔為你收集整理的spring8: di依赖注入--构造注入的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spring7: di依赖注入--设值注
- 下一篇: spring10: 引用类型的自动注入