How to set standard beans init method using annotations in spring 4?

I am studying the use of Spring 4 Java annotations, and I could not find how to set the default init method for all beans that belong to a specific configuration, without adding the @PostContruct annotation to initialize the method in all clans and none of them implement an interface InitializeBean ... I just want to do something like this:

<beans default-init-method="init"> <bean id="blogService" class="com.foo.DefaultBlogService"> </bean> <bean id="anotherBean" class="com.foo.AnotherBean"> </bean> </beans> 

So, I want to do just that with Java annotations, I want to set the default configuration of beans in the bean configuration container. Is it possible? Relations

EDIT: what I really want to do is tell Spring to run the default initialize method on all beans that I create inside the BeansConfigurations class. This means add some annotation or something that sets that all contained beans will run this initialization method by default. But, as I said, I donโ€™t want to touch the beans classes, I mean, I donโ€™t want to add the @PostConstructor annotation to each initialization method for every bean class, and I donโ€™t want every bean to implement the InitializeBean interface either

+5
source share
2 answers

You can do the following:

 @Configuration public class SomeConfig { @Bean(initMethod = "initMethodName") public SomeBeanClass someBeanClass() { return new SomeBeanClass(); } } 

It would be initMethodName that for every bean you want to call initMethodName .

You can take it one step further and implement meta-annotation , for example

 @Bean(initMethod = "initMethodNAme") public @interface MyBean { } 

and just use @MyBean instead of @Bean(initMethod = "initMethodName") in SomeConfig

+5
source

If I understand your question correctly, you want each bean to run its init method (if any) without declaring all of them in the configuration file. I think your own message already has an answer, it is default-init-method="init" . On the side of the bean classes that you want to initialize, implement the public void init() method in each of them. All of them will be called when the application starts.

0
source

Source: https://habr.com/ru/post/1214245/


All Articles