如果一个类用@Service或@Component,那么只需要用@PostConstruct修饰某个方法,该方法能在类实例化的过程中自动执行,相当于类的构造函数。同时,具备了构造函数不具备的功能。

@Component
class Test{
    @PostConstruct
    public void sayHello(){
        System.out.println("Hello!");
    }
}

  但是需要注意:

  子类实例化过程中会调用父类中的@PostConstruct方法

@Component 
class TestChild extends Test{
    @PostConstruct
    public void sayBye(){
        System.out.println("Bye!");
    }
}

  启动项目,输出如下:

Hello! 
Bye!

  转载自《慎用Spring框架-子类会调用父类的@PostConstruct方法

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-30
  • 2021-09-11
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-30
  • 2021-07-24
  • 2021-05-08
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案