我可以使用这行代码获得 bean 定义:
BeanDefinitionRegistry bdr = (BeanDefinitionRegistry) context.getAutowireCapableBeanFactory();
bdr.getBeanDefinition("myBean")
当我使用 @PostConstruct 或 InitializingBean.afterPropertiesSet 时,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
initMethodName 为 null。因此,这些并不是 XML 配置 (init-method="some") 的确切替代方案。
我想知道这种微小不一致背后的原因。以及Java中设置init-method的方法,以供学习。
最佳答案
为什么要设置init方法的名称?这似乎不切实际,因为它是在幕后完成的。但是,您可以同时使用 init 方法的多种方式,并且在 official documentation 中定义了它的行为顺序。 .
在 XML 配置中,您可以设置 init 方法,以便 Spring 容器在定义的 bean
或特定 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”.
关于java - init-method 的确切替代方案(基于 Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45894530/