【问题标题】:Call Parent class PostConstruct method instead of child class调用父类 PostConstruct 方法而不是子类
【发布时间】:2015-05-26 10:52:35
【问题描述】:

我有一个特殊的要求是调用父类 PostContruct 而不是子类

import javax.annotation.PostConstruct;

public class Parent {

    public Parent(){
        System.out.println("In parent contructor");
    }

    @PostConstruct
    public void test(){
        System.out.println("In parent post construct");
        // call the child's class method 
        this.test()
    }
}


import org.springframework.stereotype.Service;

    @Service("Child")
    public class Child extends Parent{

        public void test(){
            System.out.println("In child post construct method");
        }
    }

所以使用Spring的服务注解子类被加载,使用PostContruct注解调用子类的测试方法,但是我们的要求是调用父类,从那里我们可以调用子类的测试方法。

有什么方法可以实现相同的,我们不想引入新方法或改变方法逻辑

【问题讨论】:

  • Ehrm。如果您不覆盖该方法,那么像您在此处发布的那样做会导致堆栈溢出。创建一个从testMethod 调用的方法,并实现该方法,不要覆盖方法。在 spring 框架本身的几个类中也是如此。

标签: java spring dependency-injection postconstruct


【解决方案1】:

如果您不需要孩子的特定行为,您可以简单地不覆盖它。如果子进程中没有 textMethod,则可能会使用父进程的方法。

如果您要为孩子添加特定行为,请添加 @Override 注释并在需要时调用 super.testMethod()。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-20
    • 2016-02-14
    • 2014-01-22
    • 1970-01-01
    • 2017-11-09
    • 2011-09-04
    • 2012-02-22
    • 1970-01-01
    相关资源
    最近更新 更多