• 请不要在回答技术问题时复制粘贴 AI 生成的内容
movq
V2EX  ›  程序员

SpringBoot 第三方类作为 Bean 如何添加生命周期方法?

  •  
  •   movq · Oct 7, 2022 · 2276 views
    This topic created in 1316 days ago, the information mentioned may be changed or developed.

    《深入浅出 Spring Boot 2.x 》里面第三章讲 Bean 的生命周期的时候,说

    有时候 Bean 的定义可能使用的是第三方的类,此时可以使用注解 @Bean 来配置自定义初始化和销毁方法,如下所示

    @Bean(initMethod ="init", destroyMethod = "destroy" )
    

    意思是第三方的类不能修改源代码所以只能用 Bean 注解里面的属性来指定生命周期方法吗?

    但问题是既然不能修改源代码那么如何增加 Bean 注解呢

    4 replies    2022-10-08 09:19:33 +08:00
    chendy
        1
    chendy  
       Oct 7, 2022
    > 意思是第三方的类不能修改源代码所以只能用 Bean 注解里面的属性来指定生命周期方法吗?

    是的( xml 配置也可以(但是忘了 xml 吧))

    > 但问题是既然不能修改源代码那么如何增加 Bean 注解呢

    Bean 注解是加在自己的方法上的,不需要改别人的代码
    morgan1freeman
        2
    morgan1freeman  
       Oct 8, 2022 via iPhone
    @Bean
    public 第三方类 method() {return new 第三方类()}
    0xcaffebabe
        3
    0xcaffebabe  
       Oct 8, 2022
    继承,装饰器模式
    summerLast
        4
    summerLast  
       Oct 8, 2022
    继承 ,代理 ,装饰器 等
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   989 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 18:58 · PVG 02:58 · LAX 11:58 · JFK 14:58
    ♥ Do have faith in what you're doing.