Spring bean 标签详解
1. 标签约束
<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-2.0.xsd">
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
从上面代码中可以看出,标签约束有两种方式,一种时DTD,一种是XSD
2. 标签说明
Spring bean 标签常用的有、、、,还有子标签、、等。
2.1 import 标签
<import resource="import1.xml"/>
<import resource="classpath:org/springframework/context/support/test/*/import2.xml"/>
作用:引入其他文件,当在一个大型的项目或有很多需要配置的相关信息,可以分离功能到不同的spring.xml文件中,并在一个总的入口文件中引入,以便清晰配置文件的结构,和后期对配置文件的维护工作。
例如:
<import resource="classpath:spring/applicationContext_consumer.xml" />
<import resource="classpath:spring/applicationContext_provider.xml" />
<import resource="classpath:spring/applicationContext_database.xml" />
<import resource="classpath:spring/applicationContext_solo.xml"/>
<import resource="classpath:spring/applicationContext_disconf.xml" />
<import resource="classpath:spring/applicationContext_mq.xml"/>
<import resource="classpath*:application-cas.xml" />
<import resource="classpath*:sensitiveLog.xml" />
2.1.1 resource 属性
含义:引入文件路径,被添加spring配置文件的路径,默认从当前文件路径下查找,还有其他方式定位文件路径,如下图:
2.2 alias 标签
<alias name="service" alias="myService"/>
作用:别名标签,为bean设置别名
2.2.1 name 属性
需要被设置别名的bean的引用,一般指代 bean 的id属性
2.2.2 alias 属性
bean 的别名
2.3 description 标签
作用:描述标签,该标签当做子标签用于其他的标签之中,如bean,表示对bean的描述
<bean name="service" class="org.springframework.context.support.Service">
<property name="target" ref="assemblerTwo">
<description>ddddd</description>
</property>
</bean>
2.4 bean 标签
作用:声明一个bean对象,并将该对象添加到应用上下文中
<bean id="service" name="service" class="org.springframework.context.support.Service"
abstract="true" parent="service2" scope="prototype" primary="true"
lazy-init="true"
autowire="byType" autowire-candidate="true"
factory-bean="service2" factory-method="getResources"
depends-on="assemblerOne"
init-method="getResources" destroy-method="destroy">
<constructor-arg index="" name="" ref="" type="" value=""/>
<lookup-method name="" bean=""/>
<replaced-method name="" replacer="" />
<qualifier value="" type="" />
<meta key="" value=""/>
<property name="resources" value="context*.xml"/>
</bean>
2.4.1 子标签
2.4.1.1 constructor-arg 子标签
作用:构造函数参数,当bean使用该标签后,spring将匹配与参数相对应的构造函数,并实例化对象
<bean id="holdingBean"
class="org.springframework.beans.factory.xml.XmlBeanFactoryTests$HoldingBean">
<property name="dependingBean">
<bean
class="org.springframework.beans.factory.xml.XmlBeanFactoryTests$DependingBean">
<constructor-arg index="0"><ref bean="preparingBean1"/></constructor-arg>
<constructor-arg index="1"><ref bean="preparingBean2"/></constructor-arg>
</bean>
</property>
</bean>
<bean id="preparingBean1"
class="org.springframework.beans.factory.xml.XmlBeanFactoryTests$PreparingBean1"/>
<bean id="preparingBean2"
class="org.springframework.beans.factory.xml.XmlBeanFactoryTests$PreparingBean2"/>
-
index : 参数下标,从0开始;
-
name :参数名,匹配构造方法中与之匹配的参数名,并注入;
-
type:参数的类型,如果构造方法中存在多个相同的类型,则从左向右依次注入;
-
ref:注入值,引用当前spring上下文中存在的bean的id或name;
-
value:注入值;与ref不可并存;
2.4.1.2 lookup-method 子标签
向给定的方法注入指定的bean,可用于:一个单例模式的类需要获取相同类的不同实例
<bean id="abstractBean"
class="org.springframework.beans.factory.support.LookupMethodTests$AbstractBean">
<!-- applying to overloaded methods, and based on return type since no bean name is given -->
<lookup-method name="get"/>
<lookup-method name="getOneArgument" bean="testBean"/>
<lookup-method name="getTwoArguments" bean="testBean"/>
</bean>
<bean id="extendedBean" parent="abstractBean">
<lookup-method name="getOneArgument" bean="jedi"/>
</bean>
2.4.1.3 replaced-method 子标签
作用:方法替换
-
name :该bean需要被替换的方法名称;
-
bean :用来替换该方法的bean引用,被引用bean说明:该bean需要实现spring所提供接口MethodReplacer,其具体执行内容放置在reimplement方法中
<bean id="overrideOneMethod" class="org.springframework.beans.factory.xml.OverrideOneMethod"> <lookup-method name="getPrototypeDependency" bean="jenny"/> <lookup-method name="protectedOverrideSingleton" bean="david"/> <!-- Arbitrary method replacer --> <replaced-method name="replaceMe" replacer="reverseReplacer"> <arg-type>String</arg-type> </replaced-method> <replaced-method name="replaceMe" replacer="fixedReplacer"/> </bean>
class ReverseMethodReplacer implements MethodReplacer, Serializable { @Override public Object reimplement(Object obj, Method method, Object[] args) throws Throwable { String s = (String) args[0]; return new StringBuffer(s).reverse().toString(); } }
2.4.1.4 property 子标签
作用:为该bean所给定的属性注入值
<bean id="tas" class="org.springframework.**.NameMatchTransactionAttributeSource">
<property name="properties">
<props>
<prop key="setA*">PROPAGATION_REQUIRED</prop>
<prop key="rollbackOnly">PROPAGATION_REQUIRED</prop>
<prop key="echoException">+javax.servlet.ServletException</prop>
</props>
</property>
</bean>
<bean id="txInterceptor" class="org.springframework.**.TransactionInterceptor">
<property name="transactionManager"><ref bean="txManager"/></property>
<property name="transactionAttributeSource"><ref bean="tas"/></property>
</bean>
<bean id="txAdvisor" class="org.springframework.**.TransactionAttributeSourceAdvisor">
<property name="transactionInterceptor"><ref bean="txInterceptor"/></property>
<property name="order"><value>10</value></property>
</bean>
-
name:该bean需要被注入值的属性名称;
-
ref:注入值,引用当前spring上下文中存在的bean的id或name;
-
value: 注入值,与ref不可并存;
2.4.1.5 qualifier 子标签
作用:明确指定注入id为 beanId 的bean
<bean class="org.springframework.beans.factory.xml.QualifierAnnotationTests$Person">
<property name="name" value="Larry"/>
<qualifier value="larry"/>
</bean>
<bean class="org.springframework.beans.factory.xml.QualifierAnnotationTests$Person">
<property name="name" value="Moe Jr."/>
<qualifier type="QualifierAnnotationTests.MultipleAttributeQualifier">
<attribute key="name" value="moe"/>
<attribute key="age" value="15"/>
</qualifier>
</bean>
2.4.1.6 meta 子标签
<bean class="org.springframework.beans.factory.xml.QualifierAnnotationTests$Person">
<meta key="name" value="moe"/>
<meta key="age" value="42"/>
<property name="name" value="Moe Sr."/>
</bean>
2.4.1.7 赋值子标签
<bean id="testClient" class="org.springframework.context.conversionservice.TestClient">
<property name="bool" value="true"/>
<property name="stringList">
<list>
<value>#{'test-' + strValue + '-end'}</value>
<value>#{'test-' + strValue}</value>
<value>#{'test-' + numValue+ '-end'}</value>
<value>#{'test-' + numValue}</value>
</list>
</property>
<property name="resourceArray">
<value>classpath:test.xml</value>
</property>
<property name="resourceList">
<list>
<value>classpath:test.xml</value>
</list>
</property>
<property name="resourceMap">
<map>
<entry key="res1" value="classpath:test1.xml"/>
<entry key="res2" value="classpath:test2.xml"/>
</map>
</property>
</bean>
-
value:设置值;
-
array:数组标签;
-
map:map标签
-
list:list标签
-
set:set标签
共有属性: value-type:设置传入值的类型
2.4.2 属性
-
id 属性:声明bean的id,该id在整个配置文件中唯一
-
name 属性:声明bean的名称,在整个配置文件中该name值唯一,该值可用于依赖注入和自动装配时使用
-
class 属性:声明该bean的class对象类型,输入值为类的完整名称
<bean id="adrian2Parent" class="org.springframework.aop.aspectj.autoproxy.DummyFactoryBean" abstract="true"/>
-
abstract 属性:声明该bean是否为一个抽象(类本身可以不是抽象类),spring将不对该对象进行实例化,可将该bean做为其他bean的parent属性引用,则其他bean将继承该抽象类的属性和方法
-
parent 属性:声明该bean的父类的引用,并创建父类类型的实例化对象
<bean id="adrianParent" abstract="true"> <property name="name" value="adrian"/> </bean> <bean id="adrian" class="org.springframework.tests.sample.beans.TestBean" parent="adrianParent"> <property name="age" value="34"/> </bean>
-
scope 属性:声明bean的作用范围
可选参数:
-
singleton : 单例,由spring保证该bean在整个spring容器中只存在一个对象实例;与单例模式不同;
-
prototype: 原型模式,每次使用都将创建一个新的对象;
-
request : 在一次http请求中只存在一份对象实例,此模式只在web应用中有效;
-
session :在一次session会话中有效;
-
global session :global session作用域类似于标准的HTTP Session作用域,不过它仅仅在基于portlet的web应用中才有意义。Portlet规范定义了全局Session的概念,它被所有构成某个portlet web应用的各种不同的portlet所共享。在global session作用域中定义的bean被限定于全局portlet Session的生命周期范围内。
请注意,假如你在编写一个标准的基于Servlet的web应用,并且定义了一个或多个具有global session作用域的bean,系统会使用标准的HTTP Session作用域,并且不会引起任何错误。
-
-
primary 属性:自动注入优化,当存在多个同类型的bean时,首先以这个bean进行依赖注入
<bean id="bean1" class="org.springframework.beans.factory.FactoryBeanTests$PassThroughFactoryBean" primary="true"> <constructor-arg value="org.springframework.beans.factory.FactoryBeanTests$BeanImpl1"/> <property name="instanceName" value="beanImpl1"/> </bean> <bean id="beanImpl1" class="org.springframework.beans.factory.FactoryBeanTests$BeanImpl1"> <property name="impl2" ref="bean2"/> </bean> <bean id="bean2" class="org.springframework.beans.factory.FactoryBeanTests$PassThroughFactoryBean" primary="true"> <constructor-arg value="org.springframework.beans.factory.FactoryBeanTests$BeanImpl2"/> <property name="instanceName" value="beanImpl2"/> </bean> <bean id="beanImpl2" class="org.springframework.beans.factory.FactoryBeanTests$BeanImpl2"> <property name="impl1" ref="bean1"/> </bean>
当使用@Autowired想要注入一个这个类型的bean时,就不会因为容器中存在多个该类型的bean而出现异常。而是优先使用primary为true的bean。
不过,如果容器中不仅有多个该类型的bean,而且这些bean中有多个的primary的值设置为true,那么使用byType注入还是会出错。
-
lazy-init 属性:声明该bean是否惰性加载,可选参数true,惰性加载,即在用于使用该bean是才实例化该bean;false,反之,在spring容器启动时就加载,default同false
-
autowire 属性:设置是否对该bean的***属性进行自动装载***,以及装载的方式
<bean id="betaFactory" class="org.springframework.beans.factory.FactoryBeanTests$BetaFactoryBean" autowire="constructor"> <property name="beta" ref="beta"/> </bean>
参数类型:
- No:不自动装载
- Default : 同上;
- ByName:根据该bean的属性名称,查找与之匹配的bean,并注入
- ByType:根据该bean属性的class类型,查找与之匹配的bean,并注入
- Constructor :根据该bean的构造方法进行注入,使用此种模式,spring将从bean构造方法参数最多 向无参构造依次匹配
-
autowire-candidate 属性:自动依赖注入优化
<bean id="props1" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="properties"> <value>name=props1</value> </property> </bean> <bean id="props2" class="org.springframework.beans.factory.config.PropertiesFactoryBean" autowire-candidate="false"> <property name="properties"> <value>name=props2</value> </property> </bean> <bean id="someProps" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="properties"> <value>name=someProps</value> </property> </bean>
autowire-candidate属性设置为false,这样容器在查找自动装配对象时,将不考虑该bean,即它不会被考虑作为其它bean自动装配的候选者,但是该bean本身还是可以使用自动装配来注入其它bean的。
解决的问题:***如果一个接口有多个实现类,我们该注入哪一个的问题,一种方法是设置其中一个bean不参与自动注入。***
-
factory-bean 属性: 声明一个工厂对象,当需要使用该工厂类来生产对应的对象时,可以在其他的bean标签中引用该工厂对象来生产对象
-
factory-method 属性:工厂对象的工厂方法,用于生产特定的对象
<bean id="betaFactory" class="org.springframework.beans.factory.FactoryBeanTests$BetaFactoryBean" autowire="constructor"> <property name="beta" ref="beta"/> </bean> <bean id="gammaFactory" factory-bean="betaFactory" factory-method="getGamma"/>
-
depends-on 属性:声明该bean所依赖的bean,则被依赖的bean将在该bean之前被实例化
<bean name="service" class="org.springframework.context.support.Service"> <property name="resources" value="/org/springframework/context/support/test/context*.xml"/> </bean> <bean name="service2" class="org.springframework.context.support.Service" autowire="byName" depends-on="service"> <property name="resources" value="/org/springframework/context/support/test/context*.xml"/> </bean>
-
init-method 属性:声明该bean的初始化方法,该方法将在bean实例化后立刻执行
-
destroy-method 属性:声明该bean的销毁方法,该方法将在spring 的BeanFactory关闭时调用