Bean的基於XML配置方式
阿新 • • 發佈:2017-11-02
tro .get int import file span code cto pat
基於XML配置
Beans.xml
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" 1.默認命名空間 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2.xsi標準命名空間,用於指定自定義命名空間的Schema文件 xmlns:p="http://www.springframework.org/schema/p" 3.聲明p命名空間 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> <bean id="car" class="com.smart.ditype.Car" 4.id為bean的名稱,可以通過getbean("car")獲取容器中的Bean,class為Bean的類名 p:brand="紅旗123&CA72" 5.采用p命名空間配置Bean屬性值p:maxSpeed="100" p:price="20000.00"/> </beans>
Car.class
package com.smart.ditype; public class Car { public String brand; private String corp; private double price; private int maxSpeed; public Car() {} public Car(String brand, double price) {this.brand = brand; this.price = price; } public Car(String brand, String corp, double price) { this.brand = brand; this.corp = corp; this.price = price; } public Car(String brand, String corp, int maxSpeed) { this.brand = brand; this.corp = corp; this.maxSpeed = maxSpeed; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public int getMaxSpeed() { return maxSpeed; } public void setMaxSpeed(int maxSpeed) { this.maxSpeed = maxSpeed; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String toString(){ return "brand:"+brand+"/maxSpeed:"+maxSpeed+"/price:"+price; } }
Test
package com.smart.ditype; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.testng.annotations.*; import static org.testng.Assert.*; public class DiTypeTest { public ApplicationContext factory = null; private static String[] CONFIG_FILES = { "com/smart/ditype/beans.xml" }; @BeforeClass public void setUp() throws Exception { factory = new ClassPathXmlApplicationContext(CONFIG_FILES); } @Test public void testCar(){ Car car = (Car)factory.getBean("car"); assertNotNull(car); System.out.println(car); } }
Bean的基於XML配置方式