Tutorials

Spring Java Based Configuration


Spring Java Based Configuration


So far we have learned XML based configuration and Autowiring configuration in our previous chapters of this spring tutorials.

 

In this chapter, we are going to learn about java based configuration.

Though you will achieve the same result by java configuration that you got using either of XML configuration or Autowiring. 

But its important to learn it.

 

So here we are going to see an example of configuring the spring using java.

 

Java POJO - Student.java

package javaConfigDemo;
 
public class Student {
     
      public void checkStudent(){
            System.out.println("Checking on the student");
      }
     
}

Java Config file - ConfigFile.java

This is the class that serves as configuration and does the same task that our XML config file did in our previous tutorials.

 

This class has two important things to notice:

@Configuration → This is annotation which provides information that tells to treat the class as configuration class.

@Bean → This tells to create a bean.

 

package javaConfigDemo;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class ConfigFile {
 
      @Bean
      public Student stud(){
            return new Student();
      }
}

Test Spring

package javaConfigDemo;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class TestSpring {
 
            public static void main(String[] args) {
                       
                        ApplicationContext context = new AnnotationConfigApplicationContext(Student.class);
                        Student studBean = (Student)context.getBean("student");
                        studBean.checkStudent();
                       
            }
 
}

 

 

 

 

 



Please Share this page
Views : 85
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!