Running a method after the constructor of any derived class

前端 未结 6 962
时光说笑
时光说笑 2020-12-31 00:07

Let\'s say I have a Java class

abstract class Base {
    abstract void init();
    ...
}

and I know every derived class will have to call <

6条回答
  •  离开以前
    2020-12-31 00:21

    In addition to Bozho's recommendation, an application container is excellent for the task.

    Mark your init() method with the javax.annotation.PostConstruct annotation and a rightly configured EJB or Spring container will execute the method after the dependency injections are finished, but before the object can be used by the application.

    An example method:

    @PostConstruct
    public void init() { 
        // logic..
    }
    

    In an enterprise application you can open resources to for example the files system in the init() method. This initialization can throw exceptions and should not be called from a constructor.

提交回复
热议问题