java - init-method 的确切替代方案(基于 Java)

标签 java spring javabeans

我可以使用这行代码获得 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 为 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/

相关文章:

java - Spring-boot:需要一个名为 'entityManagerFactory' 的 bean,但找不到

java - 在 Java MVC 中正确使用 Bean

java - 无法在 WebSphere Application Server 中配置队列连接工厂

单独 JAR 文件中的 JavaBeans 类

java - 如何整合Java和Python?

java - 有没有一种简单的方法可以将我的 XML 对象转换回 Java 中的 String?

java - 如何通过 Java BufferedReader 从 Nexmo.com get-balance API 获取正确的 XML 页面?

mysql - 多对多创建 2 个表

java - 生成可执行的spring boot jar

java - 如何解析此 JSON 以提取 orderinfo JsonArray