Spring入门(3)-Spring命名空间与Bean作用域

Spring入门(3)-Spring命名空间与Bean作用域

这篇文章主要介绍Spring的命名空间和Bean作用域

0. 目录

  1. Spring命名空间
  2. Bean作用域

1. Spring命名空间

在前面的文章中,Spring的配置文件中定义了beans,除了beans之外,Spring还定义了其他的命名空间,如下:

命名空间 用途
aop 为声明切面以及将@AspectJ注解的类代理为Spring切面提供了配置元素
beans 支持声明Bean和装配Bean,是Spring最核心也是最原始的命名空间
context 为配置Spring应用上下文提供了配置元素,包括自动检测和自动装配Bean、注入非Spring直接管理的对象
jee 提供了与Java EE API的集成,例如JNDI和EJB
jms 为声明消息驱动的POJO提供了配置元素
lang 支持配置由Groovy、JRuby或BeanShell等脚本实现的Bean
mvc 启动Spring MVC的能力,例如面向注解的控制器、视图控制器和拦截器
oxm 支持Spring的对象到XML映射配置
tx 提供声明式事务配置
util 提供各种各样的工具类元素,包括把集合配置为Bean、支持属性占位符元素

AOP例子

<aop:aspectj-autoproxy proxy-target-class="true"/>

context例子

<context:annotation-config />

2. Bean作用域

所有的Spring Bean默认都是单例。但除了单例之外,我们可能有别的需求,比如说多个实例。在Bean的声明中,把scope设置为prototype即可,如下:

<?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  name="PersonBll" class="com.chzhao.springtest.PersonBll"
   scope="prototype"></bean> 
</beans>

除了prototype之外,Spring还定义了另外的作用域,如下表所示。

作用域 定义
singleton 单例
prototype 每次调用创建一个实例
request 一次http请求对应一个实例
session 一个session对应一个实例
gobal-session 在全局的http session中,每个bean定义对应一个实例
原文地址:https://www.cnblogs.com/wardensky/p/4198660.html