采用Spring管理Bean和依赖注入

1.实例化spring容器 和 从容器获取Bean对象

实例化Spring容器常用的两种方式:

方法一:

在类路径下寻找配置文件来实例化容器 [推荐使用]

ApplicationContext appContext = new ClassPathXmlApplicationContext("classpath*:/META-INF/spring/applicationContext-memcached.xml");

MemCachedManager cache = appContext.getBean(MemCachedManager.class);

方法二:

在文件系统路径下寻找配置文件来实例化容器 [这种方式可以在开发阶段使用]

ApplicationContext ctx = new FileSystemXmlApplicationContext(new String[]{“d:\\beans.xml“});

Spring的配置文件可以指定多个,可以通过String数组传入。

当spring容器启动后,因为spring容器可以管理bean对象的创建,销毁等生命周期,

所以我们只需从容器直接获取Bean对象就行,而不用编写一句代码来创建bean对象。

从容器获取bean对象的代码如下:

ApplicationContext ctx = new ClassPathXmlApplicationContext(“beans.xml”);

OrderService service = (OrderService)ctx.getBean("personService");

2.Spring实例化Bean的三种方式

以下是三种方式的例子:

1.使用类构造器实例化  [默认的类构造器]<bean id=“orderService" class="cn.itcast.OrderServiceBean"/>

2.使用静态工厂方法实例化<bean id="personService" class="cn.itcast.service.OrderFactory" factory-method="createOrder"/>
public class OrderFactory {
    public static OrderServiceBean createOrder(){   // 注意这里的这个方法是 static 的!
        return new OrderServiceBean();
    }
} 3.使用实例工厂方法实例化:<bean id="personServiceFactory" class="cn.itcast.service.OrderFactory"/>
<bean id="personService" factory-bean="personServiceFactory" factory-method="createOrder"/>public class OrderFactory {    public OrderServiceBean createOrder(){        return new OrderServiceBean();
    }
}

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

3.Bean的生命周期 (Bean的作用域)

bean的scope 属性

The scope of this bean: typically "singleton" (one shared instance, which will be returned by all calls 
to getBean with the given id), or "prototype" (independent instance resulting from each call to 
getBean). Default is "singleton". Singletons are most commonly used, and are ideal for multi- 
threaded service objects. Further scopes, such as "request" or "session", might be supported by 
extended bean factories (e.g. in a web environment). Note: This attribute will not be inherited by 
child bean definitions. Hence, it needs to be specified per concrete bean definition. Inner bean 
definitions inherit the singleton status of their containing bean definition, unless explicitly specified: 
The inner bean will be a singleton if the containing bean is a singleton, and a prototype if the 
containing bean has any other scope.

.singleton  [单例] 
eg:<bean id="personService" class="com.yinger.service.impl.PersonServiceBean" scope="singleton"></bean>

在每个Spring IoC容器中一个bean定义只有一个对象实例。

请注意Spring的singleton bean概念与“四人帮”(GoF)模式一书中定义的Singleton模式是完全不同的。

经典的GoF Singleton模式中所谓的对象范围是指在每一个ClassLoader指定class创建的实例有且仅有一个

把Spring的singleton作用域描述成一个container对应一个bean实例最为贴切。亦即,假如在单个Spring容器内定义了某个指定class的bean,

那么Spring容器将会创建一个且仅有一个由该bean定义指定的类实例。

默认情况下会在容器启动时初始化bean,但我们可以指定Bean节点的lazy-init=“true”来延迟初始化bean,这时候,只有第一次获取bean会才初始化bean。

如:<bean id="xxx" class="cn.itcast.OrderServiceBean" lazy-init="true"/>

如果想对所有bean都应用延迟初始化,可以在根节点beans设置default-lazy-init=“true“,如下:

<beans default-lazy-init="true“ ...>

.prototype [原型]

每次从容器获取bean都是新的对象。

对于prototype作用域的bean,有一点非常重要,那就是Spring不能对一个prototype bean的整个生命周期负责:容器在初始化、配置、装饰或者是

装配完一个prototype实例后,将它交给客户端,随后就对该prototype实例不闻不问了。不管何种作用域,容器都会调用所有对象的初始化生命周期回调方法。

但对prototype而言,任何配置好的析构生命周期回调方法都将不会被调用。清除prototype作用域的对象并释放任何prototype bean所持有的昂贵资源,

都是客户端代码的职责。(让Spring容器释放被prototype作用域bean占用资源的一种可行方式是,通过使用bean的后置处理器,该处理器持有要被清除的bean的引用。)

以下的三种scope只是在web应用中才可以使用

.request

.session

.global session

使用这三种配置之前要先初始化Web配置

5.xml配置方法和参数

<context:component-scan base-package="com.ibs.gbplarform.common.memcached" />

<bean id="memCachedPool" class="com.whalin.memcached.SockIOPool"

factory-method="getInstance" init-method="initialize" destroy-method="shutDown">

<constructor-arg>

<value>memCachedPool</value>

</constructor-arg>

<property name="servers">

<list>

<value>127.0.0.1:11211</value>

</list>

</property>

<property name="initConn">

<value>20</value>

</property>

<property name="minConn">

<value>10</value>

</property>

<property name="maxConn">

<value>50</value>

</property>

<property name="maintSleep">

<value>3000</value>

</property>

<property name="nagle">

<value>false</value>

</property>

<property name="socketTO">

<value>3000</value>

</property>

</bean>

<bean id="memCachedClient" class="com.whalin.memcached.MemCachedClient">

<constructor-arg>

<value>memCachedPool</value>

</constructor-arg>

</bean>

Spring的依赖注入和管理Bean的更多相关文章

  1. spring不依赖注入得到实体bean

    如题,我们一般用spring的ioc,通过配置注入接口得到这个实现类,现在通过研究公司平台框架发现还有一种方法得到spring文件配置的bean方法,举个例子(注:这个ApplicationConte ...

  2. spring的依赖注入是什么意思

    最近学习spring框架,对依赖注入有些模糊,遂上网翻阅资料,做了下列总结,原博客为CSDN 南夏的 spring的依赖注入是什么意思,侵删! Spring 能有效地组织J2EE应用各层的对象.不管是 ...

  3. SpringBoot系列: 理解 Spring 的依赖注入(一)

    ==============================Spring 的依赖注入==============================对于 Spring 程序, Spring 框架为我们提供 ...

  4. spring中依赖注入

    理解依赖注入:参考https://blog.csdn.net/taijianyu/article/details/2338311 一.依赖注入让bean与bean之间以配置文件组织在一起,而不是以硬编 ...

  5. (spring-第3回【IoC基础篇】)spring的依赖注入-属性、构造函数、工厂方法等的注入(基于XML)

    Spring要把xml配置中bean的属性实例化为具体的bean,"依赖注入"是关卡.所谓的"依赖注入",就是把应用程序对bean的属性依赖都注入到spring ...

  6. Spring的依赖注入(DI)三种方式

    Spring依赖注入(DI)的三种方式,分别为: 1.  接口注入 2.  Setter方法注入 3.  构造方法注入 下面介绍一下这三种依赖注入在Spring中是怎么样实现的. 首先我们需要以下几个 ...

  7. spring的依赖注入的最常见的两种方法

    package com.lsz.spring.action; public class User { /** * set注入 */ private String username; public vo ...

  8. Java Spring各种依赖注入注解的区别

    Spring对于Bean的依赖注入,支持多种注解方式: @Resource javax.annotation JSR250 (Common Annotations for Java) @Inject ...

  9. 一步一步深入spring(3)--spring的依赖注入方式

    对于spring配置一个bean时,如果需要给该bean提供一些初始化参数,则需要通过依赖注入方式,所谓的依赖注入就是通过spring将bean所需要的一些参数传递到bean实例对象的过程,sprin ...

随机推荐

  1. sys_init

    #!/bin/bash yum install -y wget && \ wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyu ...

  2. 新手如何学python?

    在学习Python前,你应该规划好自己的学习方向,毕竟Python的方向比较多,比如: web开发 爬虫 自动化开发(运维,测试).脚本开发 大数据(数据挖掘,数据分析) 人工智能.机器学习 选择好自 ...

  3. HDU 4057:Rescue the Rabbit(AC自动机+状压DP)***

    http://acm.hdu.edu.cn/showproblem.php?pid=4057 题意:给出n个子串,串只包含‘A’,'C','G','T'四种字符,你现在需要构造出一个长度为l的串,如果 ...

  4. k8s学习 - 概念 - Deployment

    k8s学习 - 概念 - Deployment 有了 ReplicaSet 还需要有 Deployment 的原因是希望有一个控制器能管理部署更新时候的版本控制问题.一个 Deployment 可以管 ...

  5. C# 中异常抛出捕获机制--throw / try,catch,finally

    try { messagebox.show("true"); } catch { messagebox.show("false"); } finally { m ...

  6. 【原创】一个shell脚本记录(实现rsync生产文件批量迁移功能)

    #!/bin/bash #Date:2018-01-08 #Author:xxxxxx #Function:xxxxxx #Change:2018-01-17 # #设置忽略CTRL+C信号 trap ...

  7. WMI_COM_API

    Win32_Processor // CPU 处理器 Win32_PhysicalMemory // 物理内存 Win32_Keyboard // 键盘 Win32_PointingDevice // ...

  8. 个人永久性免费-Excel催化剂功能第63波-当前选择区域的上下左右平移功能及跳转窗口左上角

    日常的Excel使用过程中,大部分的时间是在做选择单元格的操作,一般来说都是对指定单元格区域的内容进行一些数据处理.转换生成新数据的过程,那选择指定单元格的步骤,若能够尽最大程度地效率上得到加速,产出 ...

  9. C#3.0新增功能09 LINQ 基础06 LINQ 查询操作中的类型关系

    连载目录    [已更新最新开发文章,点击查看详细] 若要有效编写查询,应了解完整的查询操作中的变量类型是如何全部彼此关联的. 如果了解这些关系,就能够更容易地理解文档中的 LINQ 示例和代码示例. ...

  10. Python在office开发中的应用

    Python with Excel 有几个很好的Python模块能够方便地操作Excel的数据,包括读与写,不要求本地安装Excel.例如pandas, openpyxl, xlrd, xlutils ...