Spring公共属性注入

假设现在有两个实体类,它们的属性如下图所示。现在只有两个,我们可以很轻易的进行注入配置。可是,倘若项目中的实体类很多呢?那岂不又得在配置上花费大量时间了?有没有什么好办法减少编写配置文件呢?
首先来分析一下这两个类,他们两个都有相同的属性id和name。为了避免重复性的编写这些属性配置,可以这么来做:
在applicationContext.xml文件中使用标签将两个类的相同属性抽取出来配置到abstractBean中,与其他Bean所不同的是不需要配置class属性,而需要设置它的abstract属性为true。

<bean id="abstractBean" abstract="true" >
<property name="id" value="1"/>
<property name="name" value="neeke"/>
</bean>

接下来,配置Bean1。class属性指定为实体类Bean1,指定它的parent为abstractBean。这就意味着Bean1继承了abstractBean,也就是说Bean1拥有了abstractBean的所有属性了。所以,接下来仅仅需要配置email即可。

<bean id="bean1" class="cn.ineeke.spring.Bean1" parent="abstractBean">
<property name="email" value="neeke@ineeke.com"/>
</bean>

同理对Bean2进行配置。完整applicationContext.xml配置代码如下:

<?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-2.5.xsd">
<bean id="abstractBean" abstract="true" >
<property name="id" value="1"/>
<property name="name" value="neeke"/>
</bean>
<bean id="bean1" class="cn.ineeke.spring.Bean1" parent="abstractBean">
<property name="email" value="neeke@ineeke.com"/>
</bean>
<bean id="bean2" class="cn.ineeke.spring.Bean2" parent="abstractBean">
<property name="password" value="123456"/>
</bean>
</beans>

除非另有声明,本站遵循【署名-非商业性使用-相同方式共享 3.0 共享协议】授权。

转载原创文章请注明,转载自:Neeke[http://www.ineeke.com]

本文链接: http://www.ineeke.com/archives/springpublicpropertyinjection/

2009年1月26日 | 归档于 J2EE技术 | 没有评论
本文目前尚无任何评论.

发表评论

XHTML: 您可以使用这些标签: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">
n:-zy n:-zr n:-zan n:-xf n:-wx n:-tz n:-tt n:-ts n:-sy n:-st n:-ss n:-sk n:-qd n:-pz n:-lh n:-kun n:-ku n:-hx n:-hd n:-gt n:-gg n:-bz

NOTICE: You should type some Chinese word (like “你好”) in your comment to pass the spam-check, thanks for your patience!