采用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. 【commons-lang3工具】JAVA脱敏工具

    前言:commons-langbao中有很多方便的工具,无需我们自己去实现,能够节省很多开发时的问题: 1.工具包,引入依赖,jDK8对应的版本如下: <!-- https://mvnrepos ...

  2. Java面试常问问题及答案(非常详细)

    一:java基础1.简述string对象,StringBuffer.StringBuilder区分string是final的,内部用一个final类型的char数组存储数据,它的拼接效率比较低,实际上 ...

  3. Confluence迁移

    本次操作系统版本Centos7.3,Confluence版本5.9.9. 一.数据迁移 1.在旧Confluence上打包 “confluence和confluence-data”整个目录,默认安装的 ...

  4. 【运维实战】利用tar -g 实现简单全量备份和增量备份(带演示)

    备份产生 全量备份指完全备份,增量备份指针对上次至今的修改进行备份.linux提供tar -g可实现备份功能. 第一次运行 tar -g 备份存放目录/snapshot -czvf  备份存放目录/备 ...

  5. 该如何真正进入SEO行业?

    今天一个多年的朋友突然问我这个问题,他作为一个seo局外人,感觉SEO挺神秘,我认为要入行就要先了解一个SEO是什么职业,它的工作有那些,然后再考虑怎样进行学习或培训. 一.查看网站状态 seo人员每 ...

  6. 001-python3 初识

    一.python的起源 python是一门 解释型弱类型编程语言. 特点: 简单.明确.优雅 二.python的解释器 CPython. 官方提供的. 内部使用c语言来实现 PyPy. 一次性把我们的 ...

  7. Codeforces 760B:Frodo and pillows(二分)

    http://codeforces.com/problemset/problem/760/B 题意:有n张床m个枕头,每张床可以有多个枕头,但是相邻的床的枕头数相差不能超过1,问第k张床最多能拥有的枕 ...

  8. windows container 踩坑记

    windows container 踩坑记 Intro 我们有一些服务是 dotnet framework 的,不能直接跑在 docker linux container 下面,最近一直在折腾把它部署 ...

  9. 实战Spring4+ActiveMQ整合实现消息队列(生产者+消费者)

    引言: 最近公司做了一个以信息安全为主的项目,其中有一个业务需求就是,项目定时监控操作用户的行为,对于一些违规操作严重的行为,以发送邮件(ForMail)的形式进行邮件告警,可能是多人,也可能是一个人 ...

  10. 在 Microsoft.VisualStudio.Setup.Engine.Install(Product product, String destination, CancellationToken token)无法在相同位置或现有实例“20cc4971”的子目录上安装指定实例“ebc82a8e”的解决方案

    在所在的安装目录根目录下搜索实例 如 20cc4971 将文件夹全部删除. 一般默认安装在C盘,所以在C盘搜索实例文件夹,将其全部删除.