Spring Java Based Configuration Example

Xml based spring bean configuration is a traditional way, but now java based spring bean configuration is more popular. This is because configure spring beans with java annotation is simple and readable, you do not need to manage an extra xml file at all. Everything is written in java code. This article will just tell you how to use java annotation to define and use spring bean.

1. Xml Based vs Java Based Spring Project.

  1. Xml based spring project need to create a xml file to define spring managed beans and relationship.
  2. Java based spring project only need to create a java class which annotated with @org.springframework.context.annotation.Configuration as bean configuration manager. Then you can define spring container managed beans in this java class.
  3. Xml based spring need to use org.springframework.context.support.ClassPathXmlApplicationContext to initialize the bean context from xml file.
  4. Java based spring need to use org.springframework.context.annotation.AnnotationConfigApplicationContext to initialize the bean context from a java bean configuration class file.

2. Spring Java Annotation Based Configuration Example.

First we need to create a legacy spring maven project use STS ( Spring Tool Suite ), you can refer Xml Based Spring Configuration Example to learn how to do it.

Then edit the pom.xml file content as same with the Xml Based Spring Configuration Example pom.xml file.

Then next step is to create below three java files.

  1. BeansConfiguration.java : Spring bean configuration java file.
  2. HelloWorldBean.java : Spring bean java file.
  3. TestHelloWorldBean.java : Spring bean test java file.

java annotation based spring project files structure

2.1 HelloWorldBean.java

package com.dev2qa.beans;

/* This is a java pojo, do not need any annotation. */
public class HelloWorldBean {

    private String name;

    private String sex;

    private String email;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public HelloWorldBean(String name) {
        super();
        this.name = name;
    }

    public void sayHello(){
        StringBuffer strBuf = new StringBuffer();
        strBuf.append("Hello ");
        strBuf.append(name);
        strBuf.append(", you are a ");
        strBuf.append(sex);
        strBuf.append(", your email is ");
        strBuf.append(email);
        System.out.println(strBuf.toString());
    }

}

2.2 BeansConfiguration.java

package com.dev2qa.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.dev2qa.beans.HelloWorldBean;

/* Use @Configuration annotation to tell spring AnnotationConfigApplicationContext that this class is bean configuration java class. */
@Configuration
public class BeansConfiguration {

    /* Define each spring bean with a name. */
    @Bean(name="helloJerry")
    public HelloWorldBean getHelloWorldOne()
    {
        HelloWorldBean ret = new HelloWorldBean("Jerry");
        ret.setEmail("[email protected]");
        ret.setSex("Male");
        return ret;
    }

    @Bean(name="helloTom")
    public HelloWorldBean getHelloWorldTwo()
    {
        HelloWorldBean ret = new HelloWorldBean("Tom");
        ret.setEmail("[email protected]");
        ret.setSex("Female");
        return ret;
    }

}

2.3 TestHelloWorldBean.java

package com.dev2qa.test;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.dev2qa.beans.HelloWorldBean;
import com.dev2qa.config.BeansConfiguration;

public class TestHelloWorldBean {

    public static void main(String[] args) {

        // Create a spring context container.
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

        // Register the spring bean definition java class to load spring beans. 
        context.register(BeansConfiguration.class);
      
        /* Refresh context to avoid error java.lang.IllegalStateException: org.spring[email protected]5b37e0d2 has not been refreshed yet.*/
        context.refresh();

        // Get the first bean.
        HelloWorldBean helloJerry = (HelloWorldBean)context.getBean("helloJerry");

        // Get the second bean.
        HelloWorldBean helloTom = (HelloWorldBean)context.getBean("helloTom");

        helloJerry.sayHello();

        helloTom.sayHello();

        // Tell jvm when jvm shutdown then close this spring context and destroy all context managed beans. This is different from context.close()
        context.registerShutdownHook();

    }

}

3. Run Example.

Right click TestHelloWorldBean.java and select Run As —> Java Application, then you can get below result.

Jul 29, 2018 9:28:25 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.spring[email protected]5b37e0d2: startup date [Sun Jul 29 09:28:25 CST 2018]; root of context hierarchy
Hello Jerry, you are a Male, your email is [email protected]
Hello Tom, you are a Female, your email is [email protected]
Jul 29, 2018 9:28:25 AM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.spring[email protected]5b37e0d2: startup date [Sun Jul 29 09:28:25 CST 2018]; root of context hierarchy
(Visited 80 times, 1 visits today)
READ :   Autowire Spring Bean By Type Examples

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.