Spring 装配Bean

创建Spring配置

使用XML文件声明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-3.0.xsd”>

 

</beans>

Spring核心框架自带10个命名空间配置

命名空间

用             途

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、支持属性占位符元素

声明简单Bean

<bean id=”” class=””/>

1.        通过构造器注入

<beanid=”” class=””>

        <constructor-arg value=”” />

        <constructor-arg ref=”” />

</bean>

2.        通过工厂方法创建Bean

单例类中构造器私有化,通过静态方法返回相同的实例。

<bean id=”” class=”” factory-method=””/>

Bean的作用域

         <bean id=””class=“” scope=””>

作用域

定       义

singleton

在每个Spring容器中,一个Bean定义只有一个对象实例(默认)

prototype

允许Bean的定义可以被实例化任意次(每次调用都创建一个实例)

request

在一次HTTP请求中,每个Bean定义对应一个实例。该作用域仅在基于Web的Spring上下文(例如Spring MVC)中才有效

session

在一个HTTP session中,每个Bean定义对应一个实例。该作用域仅在基于Web的Spring上下文(例如Spring MVC)中才有效

global-session

在一个全局HTTP session中,每个Bean定义对应一个实例。该作用域仅在Portlet 上下文中才有效

初始化和销毁Bean

<bean id=”” class=”” init-method=””destroy-method=””/>

默认的init-method和destory-mehtod:在<beans>元素中使用default-init-method 和default-destroy-mehtod

3.       注入Bean普通属性

使用<property>元素:

<property name=”” value=””/>

<property name=””ref=””/>

<property name=””>

                 <bean class=””/>

</property>

使用命名空间p装配属性

<?xml version=”1.0” encoding=”UTF-8”?>

<beans xmlns=”http://www.springframework.org/schema/beans”

           xmlns:p=” http://www.springframework.org/schema/p”

           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-3.0.xsd”>

         <bean id=”” class=””

p:name1=””

p:name2-ref=””/>

</beans>

4.        装配集合

集合元素

用          途

<list>

装配list类型的数据,允许重复

<set>

装配set类型的数据,不允许重复

<map>

装配map类型的数据,名称和值可以是任意类型

<props>

装配properties类型的数据,名称和值必须是String类型

5.        使用SpEl表达式装配(了解)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值