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 needs to create an XML file to define spring-managed beans and relationships.
  2. Java-based spring project only needs to create a java class that is annotated with @org.springframework.context.annotation.Configuration as a bean configuration manager.
  3. Then you can define spring container-managed beans in this java class.
  4. XML based spring bean configuration needs to use org.springframework.context.support.ClassPathXmlApplicationContext to initialize the bean context from xml file.
  5. Java-based spring bean configuration needs 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.

  1. First, we need to create a legacy spring maven project use STS ( Spring Tool Suite ), the project name is JavaBasedSpringProject, you can refer Xml Based Spring Configuration Example to learn how to do it.
  2. Then edit the project’s pom.xml file content as same with the XML Based Spring Configuration Example pom.xml file.
  3. The next step is to create the below three java files.
  4. BeansConfiguration.java: Spring bean configuration java file.
  5. HelloWorldBean.java: Spring bean java file.
  6. TestHelloWorldBean.java: Spring bean test java file.

2.1 HelloWorldBean.java

  1. HelloWorldBean.java
    package com.dev2qa.beans;
    
    /* This is a java pojo, does 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

  1. 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

  1. 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.springframework.context.annotation.AnnotationConfigApplicationContext@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.

  1. Right-click the TestHelloWorldBean.java file and select Run As —> Java Application, then you can get the below result.
    Jul 29, 2018 9:28:25 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
    INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@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.springframework.context.annotation.AnnotationConfigApplicationContext@5b37e0d2: startup date [Sun Jul 29 09:28:25 CST 2018]; root of context hierarchy

Leave a Comment

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.