抽象类不能在Java中实例化。但是spring说了用abstract="true"。如果抽象类的状态仅由其子类实例初始化(我想我是对的),那么如果我需要在抽象类中定义的方法内使用该属性,那么…它?我有一组代码如下:
abstract="true"
class abstract A { private Something somethingObj; // getters and setters are present. public void logSomething() { try{ //some code which throws exception } catch(Exception e){ somethingObj.logIt(e);// I have some logic inlogIt method. } } }
Spring中的抽象bean与抽象类有所不同。实际上,Spring中的抽象bean甚至不必映射到任何类。以此为例:
<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 }
请注意,FooDao并且BarDao没有任何共同的父(无论是否抽象)基类。父抽象bean定义仅用于对公共属性进行分组,因此可以避免在XML中重复。
FooDao
BarDao
另一方面,引入Dao既可以继承FooDao又可以BarDao继承的抽象类是一个好主意:
Dao
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 }
但是daobean 仍然不需要定义一个类。当多个具体bean具有相同的依赖关系时,将抽象bean视为减少XML重复的一种方法。
dao