Spring 配置Bean 詳解
阿新 • • 發佈:2018-12-20
Car類(裡面有屬性有無參建構函式,記住一定要有無參的建構函式,不然會報錯)
這個裡面有建構函式的過載方法
package cn.com.day01; public class Car { /*author:命運的信徒 * date:2018/12/19 * arm:Spring 配置bean詳解 */ private String name; private double price; private int speed; public void setName(String name) { this.name = name; } public void setPrice(double price) { this.price = price; } public void setSpeed(int speed) { this.speed = speed; } @Override public String toString() { return "Car [name=" + name + ", price=" + price + ", speed=" + speed + "]"; } //必須有一個無參的構造器,不然就會報錯 public Car() { // TODO Auto-generated constructor stub } public Car(String name, double price, int speed) { super(); this.name = name; this.price = price; this.speed = speed; } public Car(String name, int speed) { super(); this.name = name; this.speed = speed; }public Car(String name, double price) { super(); this.name = name; this.price = price; } }
測試類
1.可以通過bean的id獲取相應的bean配置,這個是唯一確認的(需要型別轉化)
2.可以通過類class來獲取,但是要求配置檔案裡面這個型別的bean是唯一的(好處就是不用型別轉化,不適用)
package cn.com.day01; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestCar { public static void main(String[] args) { //1.建立IOC容器 ApplicationContext ioc=new ClassPathXmlApplicationContext("applicationContext.xml"); //2.1通過id來獲取bean Car c=(Car) ioc.getBean("car"); //2.2通過class來獲取bean,但是通過class獲取的bean的前提是在這個配置檔案裡面這個型別的bean是唯一的 //Car c1=ioc.getBean(Car.class); System.out.println(c.toString()); } }
在測試類被執行的時候,找到配置檔案,根據id找到相應的bean配置,再根據bean給相應的屬性賦值
bean配置如下
1.屬性注入
<property name="屬性名" value="屬性值"></property>
2.構造器注入
<constructor-arg name="屬性名" value="屬性值" index="0" type="java.lang.String"></constructor-arg>
如果涉及到構造器的過載的話,可以通過index和type來匹配想要的構造器
<?xml version="1.0" encoding="UTF-8"?> <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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <!-- class就是Spring要替換的物件的全路徑,id就是類名(第一個字母小寫) --> <!-- <bean id="helloWorld" class="cn.com.day01.HelloWorld"> name是setName的set+名稱,這個名稱的第一個字母小寫 <property name="name" value="Spring"></property> </bean> --> <bean id="car" class="cn.com.day01.Car" > <!-- 通過屬性注入的方式 --> <!-- <property name="name" value="Spring"></property> <property name="price" value="90" ></property> <property name="speed" value="100" ></property> --> <!-- 通過建構函式注入 --> <!-- <constructor-arg name="name" value="aodi" ></constructor-arg> <constructor-arg name="price" value="9000"></constructor-arg> <constructor-arg name="speed" value="120"></constructor-arg> --> <!-- 對於過載的構造器怎麼辦呢?通過型別和順序,二者可以混搭 --> <constructor-arg name="name" value="aodi" index="0" type="java.lang.String"></constructor-arg> <constructor-arg name="price" value="9000" type="double"></constructor-arg> </bean> </beans>