# Spring Context Configuration (using Java Classes)

In 
Published 2022-12-03

This tutorial explains to you how Spring Context Configuration is done using Java Classes. This tutorial has an example as well.

Spring context is a Spring container which is responsible for instantiating, configuring, and assembling beans by reading configuration metadata from XML files, Java annotations or both.

In order to create and configure a Spring context using Java Classes you have to create a Maven Spring project.

Here it is the Maven pom.xml file dependencies:

Add the following classes:

package com.teste.main;
 
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
import com.teste.beans.CurrentSpeed;
import com.teste.config.SpringContextConfig;
 
public class Main {
 
   public static void main (String [] args) {
     
      System.out.println("Start Java Application ...");
         
      //The Spring context is configured from a Java Class for a Java Application 
      // (Not for a Web Application)
      // FileSystemXmlApplicationContext --> used when the context is defined in an xml file.
      try (AnnotationConfigApplicationContext context 
              = new AnnotationConfigApplicationContext(SpringContextConfig.class)) {
             
         System.out.println("Spring context created ...");
          
         //GET an instance from context BY CLASS
         // SINGLETON by default in Spring
         CurrentSpeed cSpeed =  context.getBean(CurrentSpeed.class);
          
         System.out.println("Current speed = "+cSpeed.getSpeed());
          
         //Change the speed for the context bean
         cSpeed.setSpeed(20);
             
         CurrentSpeed cSpeed2 =  context.getBean(CurrentSpeed.class);
         System.out.println("Current speed = "+cSpeed2.getSpeed());
          
         //GET an instance from context BY NAME
         CurrentSpeed cSpeed3 =  context.getBean("carCurrentSpeed", CurrentSpeed.class);
         System.out.println("Current speed = "+cSpeed3.getSpeed());
          
      }
   }
}
package com.teste.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
import com.teste.beans.CurrentSpeed;
 
@Configuration
public class SpringContextConfig {
 
    @Bean
    public CurrentSpeed carCurrentSpeed() {
         
        CurrentSpeed cSpeed = new CurrentSpeed();
        cSpeed.setSpeed(10);
         
        return cSpeed;
    }
}
package com.teste.beans;

public class CurrentSpeed {
 
    private int speed;
 
    public CurrentSpeed() {
        this.speed = 0;     
    }
     
    public int getSpeed() {
        return this.speed;
    }
 
    public void setSpeed(int cSpeed) {
        this.speed = cSpeed;
    }
}

When you run the code you will se the following result :