spring框架提供了三種方式的基於xml配置依賴注入:屬性注入,構造方法注入,工廠方法注入。本文舉例演示屬性注入。spring
屬性注入是經過爲bean配置<property>標籤爲bean的注入屬性。類定義時必須定義依賴成員的public setter方法。app
例若有類MasterA框架
package com.bwf51coding.bean;ide
public class MasterA {測試 private int age;this private String name;code public int getAge() {xml return age;blog }ip public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "MasterA [age=" + age + ", name=" + name + "]"; } }
|
applicationContext.xml配置文件配置方式以下:
<bean id="mastera" class="com.bwf51coding.bean.MasterA"> <property name="age" value="20"/> <property name="name" value="Jack"/> </bean> |
測試類代碼:
package com.bwf51coding.test;
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.bwf51coding.bean.MasterA;
public class TestA { public static void main(String[] args) { ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml"); MasterA mastera=(MasterA)ac.getBean("mastera"); System.out.println(mastera); } } |