您的位置:首页 > 编程语言 > Java开发

spring bean abstract="true"

2014-09-30 10:55 344 查看
Abstract beans in Spring are somewhat different from abstract classes. In fact, abstract bean in Spring doesn't even have to be mapped to any class. Take this as an example:
<bean id="dao" abstract="true">
<property name="dataSource" ref="dataSource"/>
<property name="someHelper" ref="someHelper"/>
</bean>

<bean id="fooDao" class="FooDao" parent="dao">
<property name="fooHelper" ref="fooHelper"/>
</bean>
<bean id="barDao" class="BarDao" parent="dao">
<property name="barHelper" ref="barHelper"/>
</bean>


And classes:
public class FooDao {
private DataSource dataSource;
private SomeHelper someHelper;
private FooHelper fooHelper;

//setters
}

public class BarDao {
private DataSource dataSource;
private SomeHelper someHelper;
private BarHelper barHelper;

//setters
}


Note that 
FooDao
 and 
BarDao
 do
not have any parent (abstract or not) base class in common. Parent abstract bean definition is used only to group common
properties
, so you avoid repetition in XML.

On the other hand introducing abstract 
Dao
 class
that both 
FooDao
 and 
BarDao
 inherit
from would be a good idea:
public abstract Dao {
protected DataSource dataSource;
protected SomeHelper someHelper;

//setters
}

public class FooDao extends Dao {
private FooHelper fooHelper;

//setters
}

public class BarDao extends Dao {
private BarHelper barHelper;

//setters
}


But still 
dao
 bean
doesn't have to define a class. Treat abstract beans as a way to reduce duplication in XML when several concrete beans have same dependencies.

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐