Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 525
Charles Avatar asked Dec 24 '11 02:12

Charles


People also ask

How can we specify Init method for spring bean?

To define setup and teardown for a bean, we simply declare the <bean> with initmethod and/or destroy-method parameters. The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation.

What is @bean annotation in spring boot?

Spring @Bean Annotation is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods. In this case, bean methods may reference other @Bean methods in the same class by calling them directly.

Which annotation is used to configure the beans automatically?

The @Autowired annotation can apply to bean property setter methods, non-setter methods, constructor and properties.

Which annotation is used to perform initialization of beans?

Explanation: Using JSR annotation.


2 Answers

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");
}
like image 111
Aravind Yarram Avatar answered Oct 21 '22 01:10

Aravind Yarram


@Bean(initMethod="init")
public MyBean getMyBean() {
 ...
}
like image 30
BrentR Avatar answered Oct 21 '22 02:10

BrentR