Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

java - What is meant by abstract="true" in spring?

Abstract classes cannot be instantiated in java. But spring says something like bean creation with abstract="true". If a state of an abstract class is initialised only by its child class instance(i guess i am right), then if i need to use that attribute inside the method which is defined in the abstract class then... is there a possibility for it? I have a set of code as follows:

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. 
        } 
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...