GetBeans in a Spring Main Method, A Better Way

My Spring Data Application on GitHub is a console application. That will no doubt change in the future, but because it’s a console application there is a definite entry point that creates the Spring Application Context and wires up all of the component beans.

The way I’ve been initializing Spring and getting the party started is shown in the code below.

public static void main(String[] args) {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(SpringJpaConfiguration.class);
	ctx.refresh();

	ContactJpaService contactJpaService = (ContactJpaService) ctx.getBean("jpaContactService");
	ContactEntityService contactEntityService = (ContactEntityService) ctx.getBean("entityContactService");
	SpringProperties springProperties = ctx.getBean(SpringProperties.class);

	SpringDevelopment springDevelopment = new
		SpringDevelopment(springProperties, contactJpaService, contactEntityService);

	springDevelopment.entityDemo();

}

This works fine but is not very Spring-like, at all. I knew there was a better, more Spring-like way to instantiate my beans and launch my application.

That better way is to view my Main() method as where I initialize my application context and fetch a single bean from the application context–and nothing more. That bean, which has been wired by the Application Context will serve as the Spring application’s entry point, with the rest of the logic in the beans themselves. Here’s the new Main() whose sole function is now to fetch a new SpringApplication class.

public static void main(String[] args) {

	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(SpringConfiguration.class);
	ctx.refresh();
	SpringApplication app = ctx.getBean(SpringApplication.class);
	app.init();

}

In the SpringApplication class the beans we were retrieving directly from the application context previously in Main() are now nicely wired, with all of the injection characteristics Spring provides. The application logic begins within SpringApplication.init(), which will create threads, listen for events, and so on. And it’s prettier!

@Component
public class SpringApplication {

    @Autowired
    private ContactService contactService;

    @Autowired
    private SpringProperties springProperties;

    public void init()
    {
        SpringUI ui = new SpringUI(springProperties, contactService);
        ui.propertiesDemo();
        ui.entityDemo();
    }
}