I need to do some initialization work after bean properties set,
ApplicationContext context = new ...;
AutowireCapableBeanFactory factory = context.getAutowireCapableBeanFactory();
// autowireBean only populate the fields, but never invoke afterPropertiesSet().
factory.autowireBean(bean);
// Should I set it manually?
// if (bean instanceof InitializingBean) {
// ((InitializingBean) bean).afterPropertiesSet();
// }
// if (bean instanceof ApplicationContextAware) {
// ((ApplicationContextAware) bean).setApplica开发者_如何学编程tionContext(context);
// }
// if ...
Try this:
factory.autowireBean(bean);
bean = (YourBean) factory.initializeBean(bean, "anyName");
It works with @PostConstruct
(which I would recommend), so it should execute afterPropertiesSet()
as well. anyName
is the bean name, probably used when BeanNameAware
interface is involved.
Yes. The documentation says the method autowires the bean, and nothing else.
There are other methods in the factory that take care of initialization, but they require a bean definition.
精彩评论