0
votes

I can get a bean definition with this line of code:

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

initMethodName is null when I use either @PostConstruct or InitializingBean.afterPropertiesSet. So, those aren't the exact alternatives to XML configuration (init-method="some").

I'd like to know the reason behind this tiny inconsistency. And the way to set init-method in Java, for learning sake.

1

1 Answers

1
votes

Why do you want to set the name of the init method? This seems impractical since it's done behind the scenes. You can, however, use multiple ways of init method at the same time and there is a defined order how it would behave in the official documentation.

In XML configuration, you can set the init method, so the Spring container looks for such method in defined beans or specific bean tags, but that unnecessarily couples code to the framework and makes it a little less readable. Explicit is better than implicit.

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”.