Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Configuration Init Method

How can I tell Spring to run that init method? I need to get the Proxied Async class and do some initialization with it.

@Configuration
@EnableAsync
public class Config  {

 @Bean
 public AsyncBean asyncProxyBean(){
    return new AsyncBean();
 }

 public void init(){
   doStuffWithProxy(asyncProxyBean());
 }

 @Bean
 public String thisIsHack(){ //this runs the init code but bean is a bit hacky
    doStuffWithProxy(asyncProxyBean());
    return "";
 }

}
like image 619
DD. Avatar asked Jan 04 '12 22:01

DD.


People also ask

What is Init method in spring?

The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. Similarly, destroymethod specifies a method that is called just before a bean is removed from the container.

What is the @configuration in Spring Boot?

Spring @Configuration annotation is part of the spring core framework. Spring Configuration annotation indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application.

Does @configuration create a bean?

It is a method-level annotation. During Java configuration ( @Configuration ), the method is executed and its return value is registered as a bean within a BeanFactory .

What is Init method in Java?

In Java, an initializer is a block of code that has no associated name or data type and is placed outside of any method, constructor, or another block of code. Java offers two types of initializers, static and instance initializers.


2 Answers

You could use @PostConstruct to do this

like image 157
JustinKSU Avatar answered Sep 23 '22 01:09

JustinKSU


Use the @PostConstruct annotation along with:

  • <context:annotation-config /> or
  • <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />

See here for details. This is a Java EE annotation, so may not be appropriate in your environment.

like image 34
Dave Newton Avatar answered Sep 25 '22 01:09

Dave Newton