init-method 的确切替代方法(Java-based)

The exact alternative to init-method (Java-based)

我可以用这行代码得到一个bean定义:

BeanDefinitionRegistry bdr = (BeanDefinitionRegistry) context.getAutowireCapableBeanFactory();
bdr.getBeanDefinition("myBean")

Generic bean: class [com.kciray.play.MyBean]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null

当我使用 @PostConstructInitializingBean.afterPropertiesSet 时,

initMethodName 为空.因此,这些并不是 XML 配置 (init-method="some") 的确切替代方案。

我想知道这种微小的不一致背后的原因。以及在 Java 中设置 init-method 的方法,以供学习。

为什么要设置init方法的名字?这似乎不切实际,因为它是在幕后完成的。但是,您可以同时使用多种方式的 init 方法,并且有一个定义的顺序它在 official documentation.

中的行为方式

在XML配置中,你可以设置init方法,所以Spring容器在定义的beans或特定的bean标签中寻找这样的方法,但是不必要地将代码耦合到框架并使其可读性稍差。 显式优于隐式

The JSR-250 @PostConstruct and @PreDestroy annotations are generally considered best practice for receiving lifecycle callbacks in a modern Spring application. Using these annotations means that your beans are not coupled to Spring specific interfaces. For details see Section 7.9.8, “@PostConstruct and @PreDestroy”.