Spring框架入门之基于xml文件配置bean详解

时间:2024-08-26 14:03:44

关于Spring中基于xml文件配置bean的详细总结(spring 4.1.0)

一、Spring中的依赖注入方式介绍

  依赖注入有三种方式

  • 属性注入
  • 构造方法注入
  • 工厂方法注入(很少使用,不推荐,本文不再介绍)

  属性注入

  通过 setter 方法注入Bean 的属性值或依赖的对象。属性注入使用 <property>元素, 使用 name 属性指定 Bean 的属性名称,value 属性或 <value> 子节点指定属性值 。属性注入是实际应用中最常用的注入方式。HelloWorld类中的setName()方法,对应上边代码中的name属性,例如:把setName()方法名改为setName2(),property中的name属性值为name时则会报错,需要将name属性改为name2。


  构造方法

  构造方法注入Bean 的属性值或依赖的对象,它保证了 Bean 实例在实例化后就可以使用。
  构造器注入在 <constructor-arg> 元素里声明属性, <constructor-arg> 中没有 name 属性。使用value属性值或value子节点为属性赋值。可以同时使用索引 index 和type属性对应为哪个属性赋值。index的值表示构造函数中参数的位置。type表示成员属性的类型,例如type=“double”

二、属性注入和构造方法注入详解:

1.applicationContext.xml文件配置如下

 <?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"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd"> <!--
配置bean
class:bean的全类名,通过反射的方式在IOC容器中创建bean
id:表示容器中的bean,id唯一
-->
<!-- 通过setter注入配置bean的属性 -->
<bean id="helloWorld" class="me.spring.beans.HelloWorld">
<property name="name" value="Spring"></property>
</bean>
<!-- 通过构造方法配置bean的属性 -->
<bean id="car" class="me.spring.beans.Car">
<constructor-arg value="Audi"></constructor-arg>
<constructor-arg value="ShangHai"></constructor-arg>
<constructor-arg value="300000"></constructor-arg>
</bean> <!--
使用构造器注入的属性值可以指定参数的类型和参数的位置,以区分重载的构造器
如果字面值包含特殊字符,可以使用<![CDATA[]]>包裹起来
属性值也可以使用value子节点进行配置
-->
<bean id="car2" class="me.spring.beans.Car">
<constructor-arg value="Baoma"></constructor-arg>
<constructor-arg type="java.lang.String">
<value><![CDATA[<Beijing>]]></value>
</constructor-arg>
<constructor-arg value="240" type="int"></constructor-arg>
</bean> <!-- 可以使用property的ref属性建立bean之间的引用关系 -->
<bean id="person" class="me.spring.beans.Person">
<property name="name" value="Tom"></property>
<property name="age" value="24"></property>
<!--
<property name="car" ref="car2"></property>
--> <!--
<property name="car">
<ref bean="car2"/>
</property>
--> <!-- 内部bean,不能被外部引用 -->
<property name="car">
<bean class="me.spring.beans.Car">
<constructor-arg value="Ford"></constructor-arg>
<constructor-arg value="ChangAn"></constructor-arg>
<constructor-arg value="2354395" type="double"></constructor-arg>
</bean>
</property>
</bean> <bean id="person2" class="me.spring.beans.Person">
<constructor-arg value="Jerry"></constructor-arg>
<constructor-arg value="25"></constructor-arg>
<constructor-arg ref="car2"></constructor-arg> <!-- 测试赋值null -->
<!--
<constructor-arg><null/></constructor-arg>
-->
<!--
为级联属性赋值
注意:属性需要初始化后才可以为级联属性赋值,和Struts2不同
这里必须依据person的setter和getter方法,不能为car2
-->
<property name="car.price" value="4546"></property>
</bean> <!-- 测试如何配置集合属性 -->
<bean id="person3" class="me.spring.beans.collections.Person">
<property name="name" value="Mike"></property>
<property name="age" value="34"></property>
<property name="cars">
<!-- 使用list结点为属性为list的属性赋值 -->
<list>
<ref bean="car"/>
<ref bean="car2"/>
<bean class="me.spring.beans.Car">
<constructor-arg value="Ford"></constructor-arg>
<constructor-arg value="ChangAn"></constructor-arg>
<constructor-arg value="2354395" type="double"></constructor-arg>
</bean>
</list>
</property>
</bean>
<bean id="newPerson" class="me.spring.beans.collections.NewPerson">
<property name="name" value="Rose"></property>
<property name="age" value="23"></property>
<property name="cars">
<!-- 使用map结点及map的entry子节点配置Map类型的成员变量 -->
<map>
<entry key="AA" value-ref="car"></entry>
<entry key="BB" value-ref="car2"></entry>
</map>
</property>
</bean> <!-- 配置properties属性值 -->
<bean id="dataSource" class="me.spring.beans.collections.DataSource">
<property name="properties">
<!-- 使用props和prop子节点来为properties属性值赋值 -->
<props>
<prop key="user">root</prop>
<prop key="password">123456</prop>
<prop key="jdbcURL">jdbc:mysql://localhost:3306/test</prop>
<prop key="driverClass">com.mysql.jdbc.Driver</prop>
</props>
</property>
</bean> <!-- 配置单例的集合bean,以供多个bean进行引用,需要导入util命名空间 -->
<util:list id="cars">
<ref bean="car"/>
<ref bean="car2"/>
</util:list> <bean id="person4" class="me.spring.beans.collections.Person">
<property name="name" value="Jack"></property>
<property name="age" value="34"></property>
<property name="cars" ref="cars"></property>
</bean> <!-- 通过p命名空间为bean的属性赋值,需要导入p命名空间,相对于传统的配置较为简洁 -->
<bean id="person5" class="me.spring.beans.collections.Person" p:name="Queen" p:age="45" p:cars-ref="cars"></bean>
</beans>

2.相关的实体类:

(1)me.spring.beans 包下:

 package me.spring.beans;

 public class Car {

     private String brand;
private String corp;
private double price;
private int maxSpeed;
public Car(String brand, String corp, double price) {
super();
this.brand = brand;
this.corp = corp;
this.price = price;
} public Car(String brand, String corp, int maxSpeed) {
super();
this.brand = brand;
this.corp = corp;
this.maxSpeed = maxSpeed;
} public void setPrice(double price) {
this.price = price;
} public double getPrice() {
return price;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", corp=" + corp + ", price=" + price + ", maxSpeed=" + maxSpeed + "]";
} } package me.spring.beans; public class Person { private String name;
private int age;
private Car car; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public Car getCar() {
return car;
} public void setCar(Car car) {
this.car = car;
} public Person() { }
public Person(String name, int age, Car car) {
super();
this.name = name;
this.age = age;
this.car = car;
} @Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", car=" + car + "]";
} } package me.spring.beans; public class HelloWorld { private String name;
public void setName(String name) {
this.name = name;
}
public void hello() {
System.out.println("hello:" + name);
}
} package me.spring.beans; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) {
// HelloWorld helloWorld = new HelloWorld();
// helloWorld.setName("Spring");
// helloWorld.hello(); //1.创建Spring的IOC容器对象
//ApplicationContext代表IOC容器
//ClassPathXmlApplicationContext是ApplicationContext的实现类,该实现类从类路径下加载配置文件
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//2.从IOC容器中获取bean实例
//利用id定位到IOC容器中的bean
HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");
//利用类型返回IOC容器中的bean,担忧求IOC容器中只能有一个该类型的bean
//HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
//3.调用hello方法
helloWorld.hello();
Car car = (Car) ctx.getBean("car");
System.out.println(car);
car = (Car) ctx.getBean("car2");
System.out.println(car);
Person person = (Person) ctx.getBean("person2");
System.out.println(person);
} }

(2)me.spring.beans.collections 测试集和属性

 package me.spring.beans.collections;

 import java.util.List;

 import me.spring.beans.Car;

 public class Person {

     private String name;
private int age; private List<Car> cars; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public Person() { } public List<Car> getCars() {
return cars;
} public void setCars(List<Car> cars) {
this.cars = cars;
} public Person(String name, int age, List<Car> cars) {
super();
this.name = name;
this.age = age;
this.cars = cars;
} @Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", cars=" + cars + "]";
}
} package me.spring.beans.collections; import java.util.Map; import me.spring.beans.Car; public class NewPerson { private String name;
private int age;
private Map<String, Car> cars;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Map<String, Car> getCars() {
return cars;
}
public void setCars(Map<String, Car> cars) {
this.cars = cars;
} public NewPerson() {
// TODO Auto-generated constructor stub
}
public NewPerson(String name, int age, Map<String, Car> cars) {
super();
this.name = name;
this.age = age;
this.cars = cars;
}
@Override
public String toString() {
return "NewPerson [name=" + name + ", age=" + age + ", cars=" + cars + "]";
} } package me.spring.beans.collections; import java.util.Properties; public class DataSource { private Properties properties; public Properties getProperties() {
return properties;
} public void setProperties(Properties properties) {
this.properties = properties;
} @Override
public String toString() {
return "DataSource [properties=" + properties + "]";
} }
package me.spring.beans.collections; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main {     public static void main(String[] args) {
         ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
         Person person = (Person) ctx.getBean("person5");
        System.out.println(person);
         NewPerson newPerson = (NewPerson) ctx.getBean("newPerson");
        System.out.println(newPerson);
         DataSource dataSource = ctx.getBean(DataSource.class);
         System.out.println(dataSource.getProperties());
    }
}