抽象=“真"是什么意思?在春天? [英] What is meant by abstract="true" in spring?

查看:15
本文介绍了抽象=“真"是什么意思?在春天?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抽象类不能在java中实例化.但是 spring 说类似于用 abstract="true" 创建 bean.如果抽象类的状态仅由其子类实例初始化(我想我是对的),那么如果我需要在抽象类中定义的方法中使用该属性,那么......是否有可能它?我有一组代码如下:

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. 
        } 
    }
}

推荐答案

Spring 中的抽象 bean 与抽象类有些不同.实际上,Spring 中的抽象 bean 甚至不必映射到任何类.以此为例:

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>

和类:

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
}

请注意,FooDaoBarDao 没有任何共同的父类(抽象或非抽象)基类.父抽象 bean 定义仅用于对公共属性进行分组,因此您可以避免在 XML 中重复.

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.

另一方面,引入 FooDaoBarDao 都继承的抽象 Dao 类将是一个好主意:

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
}

但是 dao bean 仍然不需要定义一个类.当多个具体 bean 具有相同的依赖关系时,将抽象 bean 视为一种减少 XML 重复的方法.

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.

这篇关于抽象=“真"是什么意思?在春天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆