春天的抽象豆子与抽象类有些不同。事实上,Spring中的抽象豆甚至不必映射到任何类。以此为例:
<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>
和类:
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
}
请注意,并且没有任何父类(抽象或非抽象)基类共同。父抽象 Bean 定义仅用于对公共属性进行分组,因此可以避免在 XML 中重复。FooDao
BarDao
另一方面,引入既有又从中继承的抽象类将是一个好主意:Dao
FooDao
BarDao
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
}
但是bean仍然不必定义一个类。将抽象 Bean 视为当多个具体 Bean 具有相同的依赖项时减少 XML 中重复的一种方法。dao