关于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());
    }
}

Spring框架入门之基于xml文件配置bean详解的更多相关文章

  1. Spring框架入门之基于Java注解配置bean

    Spring框架入门之基于Java注解配置bean 一.Spring bean配置常用的注解 常用的有四个注解 Controller: 用于控制器的注解 Service : 用于service的注解 ...

  2. Spring学习记录(十三)---基于xml文件配置AOP

    上一篇讲了用注解配置AOP,现在讲用xml怎么配置AOP 其实逻辑是一样的,只是用xml的方法,要把这种逻辑写出来,告诉spring框架去执行. 例子:这里的例子和上一篇的例子一样.换成xml方式 / ...

  3. 用idea 创建一个spring小demo,基于xml文件配置

    1.首先,File->new->project ,进入新增项目页面 或者在 2.勾选spring,然后点击下一步 3.修改项目名称和项目位置 进入页面后 5.创建一个spring配置文件 ...

  4. idea的spring整合基于xml文件配置的mybatis报Invalid bound statement (not found): com.music.dao.MusicDao.findAll的问题

    一. 题主当时就是自己尝试整合spring和mybatis的时候遇到了这个问题,当时题主只看到了用注解的方式配置的dao层,题主用的是xml文件配置的形式, 而且坑爹的是题主的两个文件的路径写的也不一 ...

  5. (spring-第2回【IoC基础篇】)Spring的Schema,基于XML的配置

    要深入了解Spring机制,首先需要知道Spring是怎样在IoC容器中装配Bean的.而了解这一点的前提是,要搞清楚Spring基于Schema的Xml配置方案. 在深入了解之前,必须要先明白几个标 ...

  6. java struts2入门学习--基于xml文件的声明式验证

    一.知识点总结 后台验证有两种实现方式: 1 手工验证顺序:validateXxx(针对Action中某个业务方法验证)--> validate(针对Action中所有的业务方法验证) 2 声明 ...

  7. Spring框架学习笔记(3)——配置bean

    1.属性注入 (1)根据setter方法属性注入,这里使用的是property标签.需要bean属性提供对应的setter方法,比如笔记(1)里的 HelloWorld使用的就是这种方法. <! ...

  8. Spring Security入门(基于SSM环境配置)

    一.前期准备 配置SSM环境 二.不使用数据库进行权限控制 配置好SSM环境以后,配置SpringSecurity环境 添加security依赖   <dependency> <gr ...

  9. spring +springmvc+mybatis组合applicationContext.xml文件配置

    <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.spr ...

随机推荐

  1. 11g使用非duplicate方式创建物理standby要注意的问题总结

    在上篇博文中,使用了duplicate方式来创建物理standby http://blog.csdn.net/aaron8219/article/details/38434579 今天来说说在11g中 ...

  2. 苹果新的编程语言 Swift 语言进阶(三)--基本运算和扩展运算

    一 基本操作运算 1. 赋值操作 在Swift 中,能够使用赋值操作为一个常量或一个变量赋值,也能够使用多元组一次为多个常量或变量赋值. Swift 的赋值操作与其他语言最大的不同是赋值操作除了可以为 ...

  3. C#相关知识总结

    字符串相关知识   判断某字符串中包含某个字符,并过滤 if (string.Contains("*")) string = string.Replace('*',' '); // ...

  4. Web服务器、应用服务器、Web容器、反向代理服务器区别与联系

    作者: 帅虫哥 出处:www.cnblogs.com/vipyoumay/p/7455431.html(点击尾部阅读原文前往) 我们知道,不同肤色的人外貌差别很大,而双胞胎的辨识很难.有意思的是Web ...

  5. 添加用户useradd,给用户设置修改密码passwd,修改用户信息usermod,修改用户密码状态chage,删除用户userdel,查询用户及组id,切换用户su,查看当前环境变量env

    useradd 用户名 passwd 用户名,给指定用户设密码 passwd给当前用户设密码 添加一个用户系统会自动在以下文件或目录创建对应用户信息: [root@localhost ~]# grep ...

  6. NoSQL数据库

    NoSQL数据库 1.NoSQL简介 最初表示"反SQL"运动,用新型的非关系型数据库取代关系数据库:现在表示"Not only SQL"关系和非关系型数据库各 ...

  7. linux使用freetds 连接连远程服务器sqlservser2012

    1.下载:freetds-patched.tar.gz  http://www.freetds.org/software.html http://www.freetds.org/userguide/c ...

  8. iOS UITabView简写瀑布流

    代码demo 一.tabViewCell,通过image的比例高算出cell 的高度 #import "TableViewCell.h" @implementation Table ...

  9. 创建、设置和安装Windows服务

    文章大部分内容转自:http://www.cnblogs.com/greatandforever/archive/2008/10/14/1310504.html:和:http://www.cnblog ...

  10. C++模板显式实例化,隐式实例化,特化(具体化,偏特化)辨析

    最近再次看C++ PRIMER PLUS的时候看到这个部分感觉讲得很烂,前后口径不一致,所以写个辨析让自己明白的同时也希望对此不太清楚的朋友能搞懂. 总结一下,C++只有模板显式实例化(explici ...