How to set up init-method for a bean when spring is configured by annotation driven?

Charles picture Charles · Dec 24, 2011 · Viewed 40.9k times · Source

I use spring roo to build project and it's annotation driven, and there is no bean definition in XML file. All the configuration info is in *.aj file.

And now I want to set up an init method for a bean which don't have a default constructor (that bean is from the third party and it has a constructor with arguments, and I cannot remove them or give a default constructor to it.)

Is there anyone who can tell me how to do this, please?

The reason I want to do this is because I want to use applicationContext.getBean("thatBeanName") to dynamically get the bean and use it. Because the bean don't have a default constructor, I always get the error: java.lang.NoSuchMethodException: com.to.that.bean.<init>() and this is why I want to add the init-method to the bean.

Answer

Aravind Yarram picture Aravind Yarram · Dec 24, 2011

Use @PostConstruct as shown in below example. It is equivalent to init-method="initialize()"

@PostConstruct
public void initialize() {
    messages.put("English", "Welcome");
    messages.put("Deutsch", "Willkommen");
}