0

My java app is using Spring stereotype annotations (@Controller, @Component) and autowire annotations to manage dependency injections.

It is not web application, just plain jar. Also it's pure-annotation based code, i.e. no xml at all.

What is right way to initialize Spring annotation based application context and default configuration just from the main method?

setec
  • 15,506
  • 3
  • 36
  • 51

1 Answers1

5

Use @Configuration to name a AppConfig which is equivalent to applicationContext.xml.

@Configuration
public class AppConfig {

  @Bean(initMethod = "init")
  public Foo foo() {
      return new Foo();
  }

  @Bean(destroyMethod = "cleanup")
  public Bar bar() {
      return new Bar();
  }
}

And in main method to new a AnnotationConfigApplicationContext.

public static void main(String[] args) {
  ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
  Foo foo = ctx.getBean(Foo.class);
  //etc
}
Daniel Lin
  • 3,833
  • 1
  • 11
  • 4