在前面得博客依赖注入与控制反转中演示了应用spring实现ioc,在ApplicationContext.xml中有bean的配置,里面只是bean简单的应用。这篇主要是进一步学习使用bean。

一、定义

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="DaoImpl" class="Cuiyw.Spring.Dao.DaoImpl"></bean>
<bean id="ServiceImpl" class="Cuiyw.Spring.Service.ServiceImpl" scope="singleton">
<property name="dao" ref="DaoImpl"></property>
</bean>
</beans>

上面的代码是之前博客配置的,可以看到bean的基本构成。<beans/>是Sring配置文件的根节点,一个<beans/>节点里面可以有多个<bean>节点。在bean中常用两个属性:ID,Class. ID是一唯一标识,来确定是哪个bean,可以让其他bean中使用id引用。class用来指定是哪个class。同时还可以设置scope属性,scope有两种:singleton,non-singelton。singleton:单实例模式(默认,构造方法为private),整个Spring的容器中只有一个共享实例存在(singleton)。non-singelton:每次请求该bean,Spring容器都会新建立一个bean实例,然后返回给程序(request,session,prototype)。
二、创建

Bean的命名机制

id 当在Spring的窗口当中,查找某个Bean对象时,首先根据id进行查找,将其余作为Bean的默认名称,如果ID属性不存在,则根据Name属性进行查找(将其中的第一个名称作为默认的名称),如果ID和NAME都不存在根据类的名称进行查找。id---------->name--------------->类名。

Bean的别名:可以使用alias来为bean指定别名.

下面的配置文件还是在上面的xml基础上修改的。这里配置了ID为ServiceImpl的bean设置了别名。我们可以使用它的name、id、alias来获取service。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="DaoImpl" class="Cuiyw.Spring.Dao.DaoImpl"></bean>
<bean id="ServiceImpl" class="Cuiyw.Spring.Service.ServiceImpl" scope="singleton" name="ServiceA">
<property name="dao" ref="DaoImpl"></property>
</bean>
<alias name="ServiceA" alias="ServiceA1"/>
</beans>
package Cuiyw.SpringAop;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import Cuiyw.Spring.IService.IService; public class App
{
public static void main( String[] args )
{
ApplicationContext context=new ClassPathXmlApplicationContext(new String[]{"ApplicationContext.xml"});
BeanFactory factory=context;
IService service=(IService)factory.getBean("ServiceA1");
service.service("Cuiyw ServiceA1");
service=(IService)factory.getBean("ServiceA");
service.service("Cuiyw ServiceA");
service=(IService)factory.getBean("ServiceImpl");
service.service("Cuiyw ServiceImpl");
} }

三、注入

1.基本类型和string

可以使用value元素来设置,在上面的代码基础上稍作修改

<property name="baseProperty" value=""></property>
package Cuiyw.Spring.Service;

import Cuiyw.Spring.IDao.IDao;
import Cuiyw.Spring.IService.IService; public class ServiceImpl implements IService{ private IDao dao;
private int baseProperty;
public IDao getDao() {
return dao;
}
public void setDao(IDao dao) {
this.dao = dao;
}
public void service(String name) {
System.out.println(dao.sayHello(name)+" baseProperty:"+getBaseProperty());
}
public int getBaseProperty() {
return baseProperty;
}
public void setBaseProperty(int baseProperty) {
this.baseProperty = baseProperty;
}
}

对于string类型,XML解析器以String类型解析出数据,如果属性不是String类型,属性值会通过PropertyEditors转换为其他类型,比如时间类型.

2.注入bean

上面的代码中就注入了bean,在ServiceImpl中注入DaoImpl。可以使用ref来进行配置。

3.注入集合

常见的集合有list、map、set、property等,下面的代码是在ServiceImpl中定义了几个属性,然后在上下文中通过属性注入进去。为了测试,在DaoImpl中也增加了一个属性s。

package Cuiyw.Spring.Dao;

import java.util.Calendar;

import Cuiyw.Spring.IDao.IDao;

public class DaoImpl implements IDao{

    public String s;
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
public String sayHello(String name) {
int hour=Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
if(hour<6) return "凌晨早,"+name;
if(hour<12)return "早上好,"+name;
if(hour<13)return "中午好,"+name;
if(hour<18)return "下午好,"+name;
return "晚上好,"+name+", s="+s; }
}
package Cuiyw.Spring.Service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import Cuiyw.Spring.IDao.IDao;
import Cuiyw.Spring.IService.IService; public class ServiceImpl implements IService{ private IDao dao;
private int baseProperty;
private List<Object> lists;
private Set<Object> sets;
private Map<Object, Object> maps;
private Properties pros;
public IDao getDao() {
return dao;
}
public void setDao(IDao dao) {
this.dao = dao;
}
public void service(String name) {
System.out.println(dao.sayHello(name)+",baseProperty:"+getBaseProperty());
for(int i=0;i<lists.size();i++)
{
Object obj=lists.get(i);
System.out.println(obj.getClass().getName());
}
for(Object obj : sets)
{
System.out.println(obj.getClass().getName());
}
//遍历maps中的key
for (Object key : maps.keySet()) {
System.out.println("Key = " + key);
}
//遍历maps中的值
for (Object value : maps.values()) {
System.out.println("Value = " + value);
}
Set<String> pro=pros.stringPropertyNames();
Iterator<String> it=pro.iterator();
while(it.hasNext()){
Object key=it.next();
System.out.println(key+"----"+pros.getProperty((String) key));
}
}
public int getBaseProperty() {
return baseProperty;
}
public void setBaseProperty(int baseProperty) {
this.baseProperty = baseProperty;
}
public List<Object> getLists() {
return lists;
}
public void setLists(List<Object> lists) {
this.lists = lists;
}
public Set<Object> getSets() {
return sets;
}
public void setSets(Set<Object> sets) {
this.sets = sets;
}
public Map<Object, Object> getMaps() {
return maps;
}
public void setMaps(Map<Object, Object> maps) {
this.maps = maps;
}
public Properties getPros() {
return pros;
}
public void setPros(Properties pros) {
this.pros = pros;
}
}

主要是注入的配置,在list、map、set属性中都是配置了一个基础类型value=1,两个DaoImpl类型。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="DaoImpl" class="Cuiyw.Spring.Dao.DaoImpl">
<property name="s" value="cyw"></property>
</bean>
<bean id="ServiceImpl" class="Cuiyw.Spring.Service.ServiceImpl" scope="singleton" name="ServiceA">
<property name="dao" ref="DaoImpl"></property>
<property name="baseProperty" value="222"></property>
<property name="lists">
<list>
<value>1</value>
<ref bean="DaoImpl" />
<bean class="Cuiyw.Spring.Dao.DaoImpl">
<property name="s" value="cuiywlists" />
</bean>
</list>
</property>
<property name="sets">
<set>
<value>1</value>
<ref bean="DaoImpl" />
<bean class="Cuiyw.Spring.Dao.DaoImpl">
<property name="s" value="cuiywsets" />
</bean>
</set>
</property>
<property name="maps">
<map>
<entry key="key1" value="1"></entry>
<entry key="key2" value-ref="DaoImpl"></entry>
<entry key="key3" >
<bean class="Cuiyw.Spring.Dao.DaoImpl">
<property name="s" value="cuiywmaps" />
</bean>
</entry>
</map>
</property>
<property name="pros">
<props>
<prop key="prokey1">prokeyA</prop>
<prop key="prokey2">prokeyB</prop>
</props>
</property>
</bean>
<alias name="ServiceA" alias="ServiceA1"/>
</beans>

执行main方法可以看到属性都注入进去了。

4.自定义属性编辑器

对于有一些属性是没法注入的,此时就需要自定义,比如上面说的日期类型。

首先是要定义一个继承PropertyEditorSupport的类,重写setAsText方法。

package Cuiyw.Spring.Service;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat; public class CustomerProperty extends PropertyEditorSupport { private String format="yyyy-MM-dd";
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
// TODO Auto-generated method stub
SimpleDateFormat sdf=new SimpleDateFormat(format);
//super.setAsText(text);
try {
//转换对象,能过setValue方法重新赋值
this.setValue(sdf.parse(text));
} catch (ParseException e) {
e.printStackTrace();
}
} }

然后在配置文件配置这个类

<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date" value="Cuiyw.Spring.Service.CustomerProperty"/>
</map>
</property>
</bean>

这里还是在ServiceImpl中增加了一个java.util.Date类型的date属性。并在配置文件注入值。

    <property name="date" value="2017-12-10"/>

四、注入方式

package Cuiyw.Spring.Service;

import Cuiyw.Spring.IDao.IDao;

public class IOCWay {

    /*public IOCWay(IDao dao, String name) {

        this.dao = dao;
this.name = name;
System.out.println("调用构造函数实例化参数");
}
*/ private IDao dao;
private String name; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public IDao getDao() {
return dao;
} public void setDao(IDao dao) {
this.dao = dao;
} public void print()
{
System.out.println(dao.sayHello(name));
} }

上面创建了一个IOCWay类,构造函数主要是为了用来测试构造函数注入。

1.属性注入

上面用的都是属性注入。

<bean id="DaoImpl" class="Cuiyw.Spring.Dao.DaoImpl">
<property name="s" value="cyw"></property>
</bean>

2.构造函数注入  这里可以用index来设置是参数的位置

<bean id="IOCWay" class="Cuiyw.Spring.Service.IOCWay">
<constructor-arg type="java.lang.String" index="1">
<value>cuiyw</value>
</constructor-arg>
<constructor-arg ref="DaoImpl" index="0"></constructor-arg>
</bean>

3.静态工厂方式

这里先创建一个工厂类

package Cuiyw.Spring.Service;

import Cuiyw.Spring.Dao.DaoImpl;

public class IOCFactory {

    public static final DaoImpl getStaticFactoryDaoImpl(){
return new DaoImpl("cuiyw");
}
}

在配置bean时使用下面的配置,可以看到在配置属性doa时是指向了daofactory,在daofactory中配置了factory-method

<bean id="IOCWay1" class="Cuiyw.Spring.Service.IOCWay">
<property name="dao" ref="daofactory"></property>
<property name="name" value="cyw"></property>
</bean>
<bean name="daofactory" class="Cuiyw.Spring.Service.IOCFactory" factory-method="getStaticFactoryDaoImpl"></bean>

4.实例工厂方式

在上面工厂类中增加一个实例化方法。

package Cuiyw.Spring.Service;

import Cuiyw.Spring.Dao.DaoImpl;

public class IOCFactory {

    public static final DaoImpl getStaticFactoryDaoImpl(){
return new DaoImpl("cuiyw");
} public final DaoImpl getInstanceFactoryDaoImpl(){
return new DaoImpl("cuiyw");
}
}

这里还是往IOCWay注入dao和name。前面的静态工厂方法是不需要实例化工厂类的,而实例化工厂方法是需要实例化工厂类的。所以在配置factorydao时需要设置factory-bean。

<bean id="IOCWay2" class="Cuiyw.Spring.Service.IOCWay">
<property name="dao" ref="factorydao"></property>
<property name="name" value="cyw"></property>
</bean>
<bean name="daofactory" class="Cuiyw.Spring.Service.IOCFactory"></bean>
<bean name="factorydao" factory-bean="daofactory" factory-method="getInstanceFactoryDaoImpl"></bean>

上面算是把常见的4种注入方式学习了下,其实还有其他几种,已经通过注解来注入等,这里只学习了xml的注入,而且一般只有属性和构造函数常用。

Spring之bean一基础的更多相关文章

  1. [Spring]初识Spring-Spring的基础使用-如何通过Bean来实例化?

    Spring框架的基础使用 XML配置信息,Bean的不同实例化方式,注入 实例化 XML文件中的参数设置 1.通过构造器进行实例化(重点,常用方式) <bean name="aCls ...

  2. Spring基础学习笔记-Bean的基础知识

    一. Bean的定义,初始化,使用和销毁 二.ref指定依赖的三种模式 三.Bean的五种自动装配模式(autowire) 四.Bean依赖检查的4种模式:配合atuowire使用,dependenc ...

  3. 从基础知识到重写Spring的Bean工厂中学习java的工厂模式

    1.静态工厂模式其他对象不能直接通过new得到某个类,而是通过调用getInstance()方法得到该类的对象这样,就可以控制类的产生过程.顺带提一下单例模式和多例模式:  单例模式是指控制其他对象获 ...

  4. Spring中Bean的作用域、生命周期

                                   Bean的作用域.生命周期 Bean的作用域 Spring 3中为Bean定义了5中作用域,分别为singleton(单例).protot ...

  5. Spring(二)Bean入门

    一.BeanFactory介绍 1.1.Bean: 在Spring技术中是基于组件的 最基本了是最常用的单元 其实实例保存在Spring的容器当中 Bean通常被定义在配置文件当中,Bean实例化由S ...

  6. Spring中bean的配置

    先从IOC说起,这个概念其实是从我们平常new一个对象的对立面来说的,我们平常使用对象的时候,一般都是直接使用关键字类new一个对象,那这样有什么坏处呢?其实很显然的,使用new那么就表示当前模块已经 ...

  7. Spring 装配Bean

    Spring 装配Bean 装配解释: 创建应用对象之间协作关系的的行为通常称为装配(wiring),这也是依赖注入的本质 依赖注入是Spring的基础要素 一 : 使用spring装配Bean基础介 ...

  8. 理解Spring的Bean工厂

    一提到工厂,我们先来回顾前面学习过的工厂方法和抽象工厂模式: 工厂方法:针对产品维度,能够产生新的产品,也能够产生新的产品工厂,既能够扩展产品维度.可是假设我们想在普通工厂上生产产品系列,就会特别麻烦 ...

  9. Spring的Bean,AOP以及工具类初探

    1.Bean(Ioc) BeanWrapper 根据JavaDoc中的说明,BeanWrapper提供了设置和获取属性值(单个的或者是批量的),获取属性描述信息.查询只读或者可写属性等功能.不仅如此, ...

随机推荐

  1. 树莓派.安装Redis环境

    先下载安装包 cd /home/pi/Downloadswget http://download.redis.io/releases/redis-4.0.1.tar.gz 解压 tar -zxf re ...

  2. 忘记root密码,进入单用户模式修改密码

    进入单用户模式 rhel61.在系统数秒时,按下键,进入到系统引导菜单 中2.选择系统后 按“e”键 选择kernel后 按“e”键 后空格 1+回车 b:启动系统 进入到单用户模式 rhel71.在 ...

  3. pandas.DataFrame学习系列1——定义及属性

    定义: DataFrame是二维的.大小可变的.成分混合的.具有标签化坐标轴(行和列)的表数据结构.基于行和列标签进行计算.可以被看作是为序列对象(Series)提供的类似字典的一个容器,是panda ...

  4. TreeView简单的动态加载数据

    简单的小记录,省得去看控件属性详情了,基本常用的属于就几个 先是判断根节点是否存在控件中,如果不存在则创建,之前要添加了节点同样的方法 把根节点传到子节点的方法中,再判断是否在根节点里存在子节点,如果 ...

  5. 写给想成为前端工程师的同学们  ―前端工程师是做什么的?a

    前端工程师是做什么的? 前端工程师是互联网时代软件产品研发中不可缺少的一种专业研发角色.从狭义上讲,前端工程师使用 HTML.CSS.JavaScript 等专业技能和工具将产品UI设计稿实现成网站产 ...

  6. Golang源码探索(一) 编译和调试源码

    GO可以说是近几年最热门的新型语言之一了, 一般人看到分布式和大数据就会想到GO, 这个系列的文章会通过研究golang的源代码来分析内部的实现原理, 和CoreCLR不同的是, golang的源代码 ...

  7. 用js判断是否为手机浏览,如果是手机浏览就跳转到手机站

    <script type="text/javascript"> function browserRedirect() { var sUserAgent= navigat ...

  8. Thinkphp5 常量设置问题

    楼主是之前使用了thinkphp3.2快两年了,很早就听说过thinkphp的版本已经到达5了. 不过鉴于早期的版本尚未完善,并没有立即开始学习.最近做一个项目,尝试一下新的知识. 但是在使用的时候, ...

  9. mac下selenium+python环境搭建

    selenium2+python的环境搭建主要需要python和selenium 1.python mac下自带了python,可以查看版本.当然可以选择安装其它版本的python. 2.seleni ...

  10. [转载] Bitmap的秘密

    转载自http://www.infoq.com/cn/articles/the-secret-of-bitmap/ 之前已经参加过几次QCon峰会,不过今年QCon 2014 上海峰会对我来说比较特别 ...