Spring Based Configuration – Java Annotation


Spring based configuration using Annotation help you to create Spring configurations without XML.
This tutorial give you an example with most of Spring Annotation for configuration: @Configuration, @Bean (with custom bean lifecycle method), @Import, @Scope. And they’re in multi-configuration context.

I. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE (It’s OK if you use Eclipse)

II. Overview
1. Project Structure


2. Step to do

– Create Maven project
– Add Dependencies & Plugins
– Create Classes for Beans & Configuration Classes
– Create MainApplication Class
– Run Application & Enjoy Result

IV. Practice
1. Create Maven project

– Open Spring Tool Suite, on Menu, choose File -> New -> Maven Project.
– Check Create a simple project, choose Workspace Location and click Next.
– Fill all fields in Artifact group box, then click Finish.

2. Add Dependencies & Plugins

Open pom.xml, add:

3. Create Classes for Beans & Configuration Classes




Under package config, create CustomerServiceConfig.java:

@Configuration: indicates that a class will have @Bean methods and can be used by the Spring IoC container to generate bean definitions.
@Bean: the method which are annotated by @Bean will return an object that should be registered as a bean in Application Context.

Hence, above Java code will be equivalent to XML Configuration:

Now, we come to another @Configuration class with new Bean.

Under package config, create AnotherCustomerServiceConfig.java:

@Import: loads @Bean definitions from another configuration class (CustomerServiceConfig). So when calling construct method for AnnotationConfigApplicationContext, we only need to push AnotherCustomerServiceConfig.class as input parameter, all Beans from CustomerServiceConfig will be gotten automatically.
@Scope and custom init/destroy method can be annotated to Bean without adding anything in XML Configuration.

4. Create MainApplication Class

Under package main, create MainApplication.java:

5. Run Application & Enjoy Result

– Config maven build:
clean install
– Run project with mode Java Application
– Check results in Console Screen:

IV. Source Code


By grokonez | September 16, 2016.

Last updated on September 23, 2018.

Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *