下载spring包,在eclipse搭建spring环境。

这步我在eclipse中无法导入包,看网上的:

http://sishuok.(和谐)com/forum/blogPost/list/2428.html

建一个java project

三个java文件,一个xml文件

 package com.guigu.spring.beans;

 public class HelloWord {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void hello(){
System.out.println("hello: "+name);
}
}
 import java.applet.AppletContext;

 import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main {
public static void main(String[] args) {
// 传统调用方式
// HelloWord h = new HelloWord();
// h.setName("evan");
// h.hello();
//1、读取配置文件实例化一个IoC容器 ,会动态创建对象,调用构造函数,xml中有属性还会调用setname()
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
//2、从容器中的id获取Bean,注意此处完全“面向接口编程,而不是面向实现”
HelloWord hello = (HelloWord) context.getBean("helloword");
//3、执行业务逻辑
hello.hello();
} }
 <?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- id 表示你这个组件的名字,class表示组件类 -->
<bean id="helloword" class="com.guigu.spring.beans.HelloWord">
<property name="name" value="Spring"></property>
</bean>
</beans>

helloword是一个id标识,它属于com.guigu.spring.beans.HelloWord类,是它的一个实例。一个类可以有多个实例。所以可以有多个bean的类相同,表示一个类的不同实例。

bean中可以添加属性,用property属性

IoC容器

用的是ApplicationContext(应用上下文),它是由BeanFactory(Bean工厂)扩展而来,BeanFactory提供了IoC容器最基本功能如: getBean();

ApplicationContext扩展了BeanFactory,还提供了与Spring AOP集成、国际化处理、事件传播及提供不同层次的context实现。

【  ApplicationContext 的初始化和BeanFactory 有一个重大的区别:BeanFactory在初始化容器时,并未实例化Bean,直到第一次访问某个Bean 时才实例目标Bean,即调用getBean才初始化;而ApplicationContext 则在初始化应用上下文时就实例化所有单实例的Bean 。】

(了解更多去大牛博客:http://elf8848.iteye.com/blog/324796)

ApplicationContext的实现有两个:

• ClassPathXmlApplicationContext从类路径获取配置文件。

 ApplicationContext context = new ClassPathXmlApplicationContext("application.xml") 

• FileSystemXmlApplicationContext从文件系统获取配置文件。

ApplicationContext context = new FileSystemXmlApplicationContext("c:/application.xml");  

ApplicationContext获取bean的方法:

1、通过id获取容器中的bean

 ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
HelloWord hello = (HelloWord) context.getBean("helloword");

2、通过类类型获取。但是只能在HelloWord类只有一个bean对象才行,不然就不知道到底获取哪一个而报错

  ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
HelloWord hello = context.getBean(HelloWord.class); //不用类型强转,因为已经知道返回类型了

IOC容器注入依赖资源,三种注入方式:

1、属性注入(最常用)

2、构造器注入

3、工厂方法注入(很少用,不推荐)

属性注入:通过setter方法注入;使用<property>,使name属性指定bean的属性名称

 <property name="name" value="Spring"></property>

表示bean所在类有一个name属性,值是Spring

构造器注入 

用bean里的constructor-arg属性

例子--新建一个Car类

 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;
}

xml中添加,index表示对应的属性,若不写,默认按顺序匹配

 <bean id="car" class="com.guigu.spring.beans.Car">
<constructor-arg value="aodi" index="0"></constructor-arg>
<constructor-arg value="ShangHai" index="1"></constructor-arg>
<constructor-arg value="300000" index="2"></constructor-arg>
</bean>

main函数中

   ApplicationContext ctx= new ClassPathXmlApplicationContext("application.xml");
HelloWord car=ctx.getBean(Car.class);
system.out.println(car); //调用Car中的toString函数,已省略

输出结果:Car [brand=aodi, corp=ShangHai, price=300000, maxSpeed=0];

若构造函数是多个呢?重载的构造函数,xml中对应哪一个呢?

 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;
}
  <bean id="car2" class="com.guigu.spring.beans.Car">
<constructor-arg value="aodi" type="java.lang.String"></constructor-arg> //除基本类型外,其余都要写全类名
<constructor-arg value="ShangHai" type="java.lang.String"></constructor-arg>
<constructor-arg value="240" type="int"></constructor-arg> //基本类型,不用谢全类名
</bean>
    ApplicationContext ctx= new ClassPathXmlApplicationContext("application.xml");
HelloWord car=ctx.getBean("car");
system.out.println(car);
HelloWord car=ctx.getBean("car2");
system.out.println(car);

输出结果:

Car [brand=aodi, corp=ShangHai, price=300000.0, maxSpeed=0];

Car [brand=aodi, corp=ShangHai, price=0.0, maxSpeed=240];

总结:通过构造器方法时,可以用参数的位置和参数的类型来区分重载构造函数,位置和参数是可以同时使用,如下

  <bean id="car" class="com.guigu.spring.beans.Car">
<constructor-arg value="aodi" index="0"></constructor-arg>
<constructor-arg value="ShangHai" index="1"></constructor-arg>
<constructor-arg value="240" type="int"></constructor-arg>
</bean>

细节1:value用节点表示

   <bean id="car" class="com.guigu.spring.beans.Car">
<constructor-arg value="aodi" index="0"></constructor-arg>
<constructor-arg value="ShangHai" index="1"></constructor-arg>
<constructor-arg type="int">
<value>240</value>
</constructor-arg>
</bean>

这个可以解决value是特殊字符的问题 如:<ShangHai> ,直接字面写就报错,用value节点再结合<![CDATA[]]解决

    <bean id="car" class="com.guigu.spring.beans.Car">
<constructor-arg value="aodi" index="0"></constructor-arg>
<constructor-arg index="1">
<value><![CDATA[<ShangHai>]]></value> // 值是:<ShangHai>
</constructor-arg>
<constructor-arg value="240" type="int">
</constructor-arg>
</bean>

细节2:属性是引用类型 ref元素或ref属性

若又一个Person类,有一个Car属性,Car就是前面的对象

   public class Person{
private String name;
private Car car;
} public void setName(String name){
this.name=name;
}
public getName(){
return name;
}
public void setCar(Carcar){
this.car=car;
}
public getCar(){
return car;
} }

用ref="car2" 指向之前的car2对象,来引用;同样可以改成节点式<ref bean="car2"/>

  <bean id="person" class="com.guigu.spring.beans.Person">
<property name="name" value="Tom"></proerty>
<property name="car" ref="car2"></proerty>
</bean>

细节3:内部bean,达到和引用的目的。但这个bean不能被外部引用,只能自己内部使用

   <bean id="person" class="com.guigu.spring.beans.Person">
<property name="name" value="Tom"></proerty>
<property name="car">
<bean class="com.guigu.spring.beans.Car">
<constructor-arg value="Ford"></constructor-arg>
<constructor-arg value="ChangAn"></constructor-arg>
<constructor-arg value="200000" type="double"></constructor-arg>
</bean>
</proerty>
</bean>

细节4:赋空值: <null/>;或者,直接不写就行。

  <bean id="person" class="com.guigu.spring.beans.Person">
<property name="name" value="Tom"></proerty>
<property name="car">
<bean class="com.guigu.spring.beans.Car">
<constructor-arg value="Ford"></constructor-arg>
<constructor-arg value="ChangAn"></constructor-arg>
<constructor-arg><null/></constructor-arg>
</bean>
</proerty>
</bean>

细节5:像struts一样,可以为级联属性赋值。它调用了改属性的set方法,所以类中必须要有改属性的set方法。

   <bean id="person" class="com.guigu.spring.beans.Person">
<constructor-arg
name
="name" value="Tom"></constructor-arg>  <constructor-arg name="car" ref="car2">  <property name="car.maxSpeed" value="230"></property> //   </constructor-arg>  </bean>

注意:和struts不同,不能不初始化直接赋值

     <bean id="person" class="com.guigu.spring.beans.Person">
<property name="name" value="Tom"></proerty>
<!--
<property name="car">
<bean class="com.guigu.spring.beans.Car">
<constructor-arg value="Ford"></constructor-arg>
<constructor-arg value="ChangAn"></constructor-arg>
<constructor-arg value="200000" type="double"></constructor-arg>
</bean>
</proerty>
-->
<property name="car.maxSpeed" value="260"></property>
</bean>

这里的意思是,不创建car对象,直接对它的属性赋值。

在struts中可以,会自动先创建一个car对象,然后赋值。二spring不可以,必须先初始化一个对象,再赋值。

细节6:集合属性赋值

一个person可以有多个car,怎么表示?  如下,用节点<list>  。数组list和Set与集合类似。也可以用内部bean

     public class Person{
private String name;
private List<Car> cars;
} public void setName(String name){
this.name=name;
}
public getName(){
return name;
}
public void setCar(List<Car> cars){
this.cars=cars;
}
public List<Car> getCars(){
return cars;
} }
    <bean id="person1" class="com.guigu.spring.beans.Person">
<constructor-arg name="name" value="Tom"></constructor-arg>
<property name="car">
<list>
<ref bean="car1"/>
<ref bean="car2"/>
</list>
</property >
</bean>

注意:集合中Map又不一样,因为它是键值对,用<map>、entry

 public class NewPerson{
private String name;
private Map<String, Car> cars; public String getName(){
return name;
}
public void setName(){
this.name=name;
}
public Map<String, Car> getCars(){
return cars;
}
public void setCars(Map<String, Car> cars) {
this.cars=cars;
}
     <bean id="newPerson" class="com.guigu.spring.beans.Person">
<property name="name" value="evan"></property >
<property name="cars">
<map>
<entry key="AA" value-ref="car"/>
<entry key="BB" value-ref="car2"/>
</map>
</property >
</bean>

细节7:配置properties 。 一个DataSource类,xml配置properties。如连接数据库

 public class DataSource{
private Properties properties;
public Properties getProperties(){
return properties;
}
public void setProperties(Properties properties){
this.properties = properties;
}
 <bean id="dataSource" class="com.guigu.spring.beans.DataSource">
<property name="properties">
<props>
<prop key="user">root<prop>
<prop key="password">1234<prop>
<prop key="jdbcUrl">jdbc:mysql://test<prop>
</prop>
<properties>
</bean>
 DataSource datasource = ctx.getBean(DataSource.class);
System.out.print(datasource.getProperties);

输出:

{user=root, password=1234, jdbcUrl=jdbc://test}

细节8:上面集合的配置,如果多个对象要使用,怎么提高内部属性的利用率<props>、<map>。用一个util命名空间

//单独拿出来,可以供多个bean调用
<util:list id="cars">
  <ref bean="car"/>
  <ref bean="car2"/>
</util:list>
//引用
<bean id="person3" class="com.guigu.spring.beans.Person">
<property name="name" value="jack"></property >
<property name="cars" ref="cars"></property >
</bean>

Spring学习记录(二)---容器和bean属性配置的更多相关文章

  1. Spring学习笔记(二)之装配Bean

    一,介绍Bean的装配机制 在Spring中,容器负责对象的创建并通过DI来协调对象之间的关系.但是我们要告诉Spring创建哪些Bean并且如何将其装配在一起.,装配wiring就是DI依赖注入的本 ...

  2. Spring学习系列(二) 自动化装配Bean

    一.Spring装配-自动化装配 @Component和@ComponentScan 通过spring注解(@Component)来表明该类会作为组件类,并告知Spring要为这类创建bean,不过组 ...

  3. Spring学习记录(二)

    1.Spring中的AOP思想 aop思想:横向重复,纵向抽取. AOP(Aspect-OrientedProgramming,面向切面编程),AOP包括切面(Aspect),通知(Advice),连 ...

  4. Spring 学习指南 第三章 bean的配置 (未完结)

    第三章 bean 的配置 ​ 在本章中,我们将介绍以下内容: bean 定义的继承: 如何解决 bean 类的构造函数的参数: 如何配置原始类型 (如 int .float 等) .集合类型(如 ja ...

  5. 我的Spring学习记录(二)

    本篇就简单的说一下Bean的装配和AOP 本篇的项目是在上一篇我的Spring学习记录(一) 中项目的基础上进行开发的 1. 使用setter方法和构造方法装配Bean 1.1 前期准备 使用sett ...

  6. Spring Boot学习记录(二)--thymeleaf模板 - CSDN博客

    ==他的博客应该不错,没有细看 Spring Boot学习记录(二)--thymeleaf模板 - CSDN博客 http://blog.csdn.net/u012706811/article/det ...

  7. spring 学习(二):spring bean 管理--配置文件和注解混合使用

    spring 学习(二)spring bean 管理--配置文件和注解混合使用 相似的,创建 maven 工程,配置pom.xml 文件,具体可以参考上一篇博文: sprint 学习(一) 然后我们在 ...

  8. 我的Spring学习记录(四)

    虽然Spring管理这我们的Bean很方便,但是,我们需要使用xml配置大量的Bean信息,告诉Spring我们要干嘛,这还是挺烦的,毕竟当我们的Bean随之增多的话,xml的各种配置会让人很头疼. ...

  9. 我的Spring学习记录(五)

    在我的Spring学习记录(四)中使用了注解的方式对前面三篇做了总结.而这次,使用了用户登录及注册来对于本人前面四篇做一个应用案例,希望通过这个来对于我们的Spring的使用有一定的了解. 1. 程序 ...

随机推荐

  1. 一个神奇的POS -扫描 现场销售 开单打印票据 安卓物联网POS机 手持开单终端机 省时省力 高效准确!!

    5寸高清彩屏,高端大气上档次,小巧轻便,独特的包胶防护,坚固耐用,外形精细,美观!与软件灵活对接,解决企业手工盘点,手工输单,库存管理等困难,提高准确率,提高工作效率!! 应用领域:适用于仓库.超市. ...

  2. 如何让eclipse进行智能提示?

    1.打开eclipse工具,点击window菜单,选择preferences选项 2.然后,选择Java->Editor->content assist 3.然后在Auto activat ...

  3. C# uploadify 上传 -220 IO Error 问题

    1. 前端: uploadify 上文件大小限制配置. 2. 后端: web.config 配置 <?xml version="1.0"?> <configura ...

  4. C语言_第五章__实践(密码转换)

    1.   要求 输入China  输出 Glmre #include <stdio.h> #include <stdlib.h> int main() { char c ; c ...

  5. 插头dp

    插头dp 感受: 我觉得重点是理解,算法并不是直接想出怎样由一种方案变成另一种方案.而是方案本来就在那里,我们只是枚举状态统计了答案. 看看cdq的讲义什么的,一开始可能觉得状态很多,但其实灰常简单 ...

  6. Torch7学习笔记(一)CmdLine

    该类主要为了提供一种方便解析参数的框架,对于每个实验尤其是神经网络中要调参数上.同时还可以把输出重定向到log文件中. 一般用法: cmd = torch.CmdLine() cmd:text() c ...

  7. 基于黑名单的xss过滤器

    /** * 类名称:AntiXssFilter * @version * 类描述:基于黑名单的xss过滤器 * @version * 创建人:xxx * @version * 创建时间:2015年11 ...

  8. 八大排序算法Java

    目录(?)[-] 概述 插入排序直接插入排序Straight Insertion Sort 插入排序希尔排序Shells Sort 选择排序简单选择排序Simple Selection Sort 选择 ...

  9. jquery修改Switchery复选框的状态

    script //选择框 var mySwitch; /* * 初始化Switchery * * classNmae class名 */ function initSwitchery(classNam ...

  10. bzoj2599: [IOI2011]Race(点分治)

    写了四五道点分治的题目了,算是比较理解点分治是什么东西了吧= = 点分治主要用来解决点对之间的问题的,比如距离为不大于K的点有多少对. 这道题要求距离等于K的点对中连接两点的最小边数. 那么其实道理是 ...