一、自动装配 Autowired

Spring IOC 容器可以自动装配 Bean. 需要做的仅仅是在 的 autowire 属性里指定自动装配的模式

  • byType: 根据类型进行自动装配. 但要求 IOC 容器中只有一个类型对应的 bean, 若有多个则无法完成自动装配.
  • byName: 若属性名和某一个 bean 的 id 名一致, 即可完成自动装配. 若没有 id 一致的, 则无法完成自动装配
<bean id="service" class="com.hp.spring.ref.Service" autowire="byName"></bean>

<bean id="action" class="com.hp.spring.ref.Action" autowire="byType"></bean>

二、bean的作用于singleton,prototype

默认情况下 bean 是单例的!

但有的时候, bean 就不能使单例的. 例如: Struts2 的 Action 就不是单例的! 可以通过 scope 属性来指定 bean 的作用域

  • prototype: 原型的. 每次调用 getBean 方法都会返回一个新的 bean. 且在第一次调用 getBean 方法时才创建实例
  • singleton: 单例的. 每次调用 getBean 方法都会返回同一个 bean. 且在 IOC 容器初始化时即创建 bean 的实例. 默认值
<bean id="dao2" class="com.hp.spring.ref.Dao" scope="prototype"></bean>

三、引入外部资源properties文件

    <!-- 导入外部的资源文件 -->
<context:property-placeholder location="classpath:db.properties"/> <!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean>

db.properties

jdbc.user=root
jdbc.password=root
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///test
jdbc.initPoolSize=5
jdbc.maxPoolSize=10

四、SpEL表达式 (可以为属性进行动态的赋值)

例子中,使用#{girl.userName}将bean为girl的userName动态注入到bean为boy的对象中

    <!-- 测试 SpEL: 可以为属性进行动态的赋值 -->
<bean id="girl" class="com.hp.spring.helloworld.User">
<property name="userName" value="测试"></property>
</bean> <bean id="boy" class="com.hp.spring.helloworld.User" >
<property name="userName" value="测试姓名"></property>
<property name="wifeName" value="#{girl.userName}"></property>
</bean>

关于SpEL的使用,查看 SpEL的使用.md

五、通过工厂方式类创建bean

1 使用静态工厂来创建bean

    <!-- 在 class 中指定静态工厂方法的全类名, 在 factory-method 中指定静态工厂方法的方法名 -->
<bean id="dateFormat" class="java.text.DateFormat" factory-method="getDateInstance">
<!-- 可以通过 constructor-arg 子节点为静态工厂方法指定参数 -->
<constructor-arg value="2"></constructor-arg>
</bean>

测试代码

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans-auto.xml");
DateFormat dateFormat = (DateFormat) ctx.getBean("dateFormat");
System.out.println(dateFormat.format(new Date()));

打印出:

2016-7-3

2 使用实例工厂来创建bean

    <!-- ①. 创建工厂对应的 bean -->
<bean id="simpleDateFormat" class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd hh:mm:ss"></constructor-arg>
</bean> <!-- ②. 有实例工厂方法来创建 bean 实例 -->
<!-- factory-bean 指向工厂 bean, factory-method 指定工厂方法(了解) -->
<bean id="datetime" factory-bean="simpleDateFormat" factory-method="parse">
<!-- 通过 constructor-arg 执行调用工厂方法需要传入的参数 -->
<constructor-arg value="1990-12-12 12:12:12"></constructor-arg>
</bean>

测试代码

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans-auto.xml");
Date date = (Date) ctx.getBean("datetime");
System.out.println(date);

打印出:

Wed Dec 12 00:12:12 CST 1990

六、通过FactoryBean方式创建bean

    <!-- 配置通过 FactroyBean 的方式来创建 bean 的实例(了解) -->
<bean id="user" class="com.hp.spring.ref.UserBean"></bean>

UserBean这个类需要实现FactoryBean借口

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.FactoryBean;
import com.hp.spring.helloworld.Car;
import com.hp.spring.helloworld.User;
public class UserBean implements FactoryBean<User>{
/**
* 返回的 bean 的实例
*/
@Override
public User getObject() throws Exception {
User user = new User();
user.setUserName("abc");
user.setWifeName("ABC"); List<Car> cars = new ArrayList<>();
cars.add(new Car("ShangHai", "BuiKe", 180, 300000));
cars.add(new Car("ShangHai", "CRUZE", 130, 150000)); user.setCars(cars);
return user;
}
/**
* 返回的 bean 的类型
*/
@Override
public Class<?> getObjectType() {
return User.class;
}
/**
* 返回的 bean 是否为单例的
*/
@Override
public boolean isSingleton() {
return true;
}
}

关于User类跟Car类,则是User引用了一个Car类的集合

其中,测试代码:

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans-auto.xml");
User user = (User) ctx.getBean("user");
System.out.println(user);

打印出:

User [userName=abc, cars=[Car [company=ShangHai, brand=BuiKe, maxSpeed=180, price=300000.0], Car [company=ShangHai, brand=CRUZE, maxSpeed=130, price=150000.0]]]

七、使用init-method="init" destroy-method="destroy"在bean的初始化和销毁的时候调用

    <bean id="user" class="com.hp.spring.helloworld.User" init-method="init" destroy-method="destroy">
</bean>

User类中有init和destroy方法

    public void init(){
System.out.println("init method...");
} public void destroy(){
System.out.println("destroy method...");
}

整个系列项目代码: http://git.oschina.net/nmc5/spring

spring其他配置 (3)的更多相关文章

  1. Spring Boot -- 配置切换指南

    一般在一个项目中,总是会有好多个环境.比如: 开发环境 -> 测试环境 -> 预发布环境 -> 生产环境 每个环境上的配置文件总是不一样的,甚至开发环境中每个开发者的环境可能也会有一 ...

  2. spring 定时任务配置

    1.(易)如何在spring中配置定时任务? spring的定时任务配置分为三个步骤: 1.定义任务 2.任务执行策略配置 3.启动任务 (程序中一般我们都是到过写的,直观些) 1.定义任务 < ...

  3. 两种流行Spring定时器配置:Java的Timer类和OpenSymphony的Quartz

    1.Java Timer定时 首先继承java.util.TimerTask类实现run方法 import java.util.TimerTask; public class EmailReportT ...

  4. Spring Cloud 配置服务

    Spring Cloud 配置服务 1. 配置服务简介 产生背景: 传统开发中,我们通常是将系统的业务无关配置(数据库,缓存服务器)在properties中配置,在这个文件中不会经常改变,但随着系统规 ...

  5. spring事务配置详解

    一.前言 好几天没有在对spring进行学习了,由于这几天在赶项目,没有什么时间闲下来继续学习,导致spring核心架构详解没有继续下去,在接下来的时间里面,会继续对spring的核心架构在继续进行学 ...

  6. spring MVC配置详解

    现在主流的Web MVC框架除了Struts这个主力 外,其次就是Spring MVC了,因此这也是作为一名程序员需要掌握的主流框架,框架选择多了,应对多变的需求和业务时,可实行的方案自然就多了.不过 ...

  7. Spring mvc 配置详解

    现在主流的Web MVC框架除了Struts这个主力 外,其次就是Spring MVC了,因此这也是作为一名程序员需要掌握的主流框架,框架选择多了,应对多变的需求和业务时,可实行的方案自然就多了.不过 ...

  8. Spring动态配置多数据源

    Spring动态配置多数据源,即在大型应用中对数据进行切分,并且采用多个数据库实例进行管理,这样可以有效提高系统的水平伸缩性.而这样的方案就会不同于常见的单一数据实例的方案,这就要程序在运行时根据当时 ...

  9. 为什么在Spring的配置里,最好不要配置xsd文件的版本号

    为什么dubbo启动没有问题? 原文链接:http://www.tuicool.com/articles/YRn67zM 这篇blog源于一个疑问: 我们公司使了阿里的dubbo,但是阿里的开源网站h ...

  10. Spring事务配置的五种方式(转发)

    Spring事务配置的五种方式(原博客地址是http://www.blogjava.net/robbie/archive/2009/04/05/264003.html)挺好的,收藏转发 前段时间对Sp ...

随机推荐

  1. 【leetcode】667. Beautiful Arrangement II

    题目如下: Given two integers n and k, you need to construct a list which contains ndifferent positive in ...

  2. loadrunner——win7+LR11配置

    一. 安装vmware虚拟机 下载安装vmware15后,可使用密钥为:CG392-4PX5J-H816Z-HYZNG-PQRG2 二. 安装win7系统 2.1下载win7镜像文件 2.2 vmwa ...

  3. gensim中TaggedDocument 怎么使用

    我有两个目录,我想从中读取它们的文本文件并给它们贴上标签,但我不知道如何通过taggedDocument来实现这一点.我以为它可以作为标记文档([strings],[labels])工作,但这显然不起 ...

  4. bzoj1211树的计数 x bzoj1005明明的烦恼 题解(Prufer序列)

    1211: [HNOI2004]树的计数 Time Limit: 10 Sec  Memory Limit: 162 MBSubmit: 3432  Solved: 1295[Submit][Stat ...

  5. A. Srdce and Triangle--“今日头条杯”首届湖北省大学程序设计竞赛(网络同步赛)

    如下图这是“今日头条杯”首届湖北省大学程序设计竞赛的第一题,作为赛后补题 题目描述:链接点此 这套题的github地址(里面包含了数据,题解,现场排名):点此 Let  be a regualr tr ...

  6. Future初次使用理解

    当客户端执行方法时,立即返回一个代理对象,此时代理对象没有数据,与此同时开启一个线程去构造真实对象并把真实对象替换掉代理对象(使用set方法).所以就会出现,客户端收到代理对象之后以为执行完了然后执行 ...

  7. Linux上VNC 启动和关闭

    查询vnc的线程: [admin@cn2-uat-esb-01-0001 ~]$ ps -ef|grep vncadmin 19080 21305 0 10:04 pts/2 00:00:00 gre ...

  8. opencv bwlabel

    int bwLabel(const Mat& imgBw, Mat& imgLabeled) { Mat imgClone = Mat(imgBw.rows + , imgBw.col ...

  9. 一份完整的 Java 成神路线图,值得收藏!

    Java,是现阶段中国互联网公司中,覆盖度最广的研发语言. 有不少朋友问,如何深入学习Java后端技术栈,今天分享一个,互联网牛人整理出来的完整的Java成神路线图. 一:常见模式与工具 学习Java ...

  10. Redis数据结构之整数集合-intset

    当一个集合只包含整数值元素,并且这个集合的元素数量不多时,Redis会使用整数集合(intset)来存储集合元素. intset是紧凑的数组结构,同时支持16位.32位和64位整数. 结构 struc ...