spring framework 依赖注入高级特性

Spring Framework:4.3.14.RELEASE

p 命名空间

p 命名空间是简化 property 标签的

1
2
3
4
5
6
7
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="classic" class="com.example.ExampleBean">
<property name="email" value="[email protected]"/>
</bean>
<bean name="p-namespace" class="com.example.ExampleBean" p:email="[email protected]"/>
</beans>

包含引用属性:

1
2
3
4
5
6
7
8
9
10
11
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="john-classic" class="com.example.Person">
<property name="name" value="John Doe"/>
<property name="spouse" ref="jane"/>
</bean>
<bean name="john-modern" class="com.example.Person" p:name="John Doe" p:spouse-ref="jane"/>
<bean name="jane" class="com.example.Person">
<property name="name" value="Jane Doe"/>
</bean>
</beans>

c 命名空间

c 命名空间是简化 constructor-arg 标签

1
2
3
4
5
6
7
8
9
10
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="bar" class="x.y.Bar"/> <bean id="baz" class="x.y.Baz"/>
<bean id="foo" class="x.y.Foo">
<constructor-arg ref="bar"/>
<constructor-arg ref="baz"/>
<constructor-arg value="[email protected]"/>
</bean>
<bean id="foo" class="x.y.Foo" c:bar-ref="bar" c:baz-ref="baz" c:email="[email protected]"/>
</beans>

使用索引:

1
<bean id="foo" class="x.y.Foo" c:_0-ref="bar" c:_1-ref="baz"/>

级联属性

1
2
3
<bean id="foo" class="foo.Bar">
<property name="fred.bob.sammy" value="123" />
</bean>

depends-on属性

depends-on 属性用于显式声明依赖初始化的先后顺序

1
2
<bean id="beanOne" class="ExampleBean" depends-on="manager"/> 
<bean id="manager" class="ManagerBean" />

上述说明在实例化 beanOne 前需要先实例化 manager

1
2
3
4
5
<bean id="beanOne" class="ExampleBean" depends-on="manager,accountDao"> 
<property name="manager" ref="manager" />
</bean>
<bean id="manager" class="ManagerBean" />
<bean id="accountDao" class="x.y.jdbc.JdbcAccountDao" />

lazy-init属性

容器启动时默认对 Bean 进行初始化。 lazy-init 可以对 Bean 设置延迟初始化,当第一次访问时再去初始化。

1
2
<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/> 
<bean name="not.lazy" class="com.foo.AnotherBean"/>

还可以批量设置启用:

1
2
3
<beans default-lazy-init="true">

</beans>