Using Spring AnnotationConfigApplicationContext

Overview

Using the AnnotationConfigApplicationContext

  • We will learn how to use the AnnotationApplicationContext. We are going to create a standalone spring application, using the AnnotationApplicationContext.
  • In this example, we have two classes:

Music Class:



@Component
public class Music {
    @Autowired private String genre;
    public void setGenre(String genre) {
        this.genre = genre;
    }
    @Override
    public String toString() {
    return "Music{" + "Genre='" + genre + ''' + '}';
    }
} 

Piano class:


@Component
public class Piano {
    @Autowired
    private Music rawMusic;
    private String numberOfKeys;
    @ConstructorProperties({"rawMusic", "pianoKeys"})
    public Piano(Music music, String numberOfKeys) {
        this.rawMusic = music;
        this.numberOfKeys = numberOfKeys;
    }
    @Override
    public String toString() {
        return "Piano{" +
                "pianoMusic=" + rawMusic +
                ", numberOfKeys='" + numberOfKeys + ''' +
                '}';
    }
}

Spring Configuration

  • Now we have the POJO’s, now we are going to use the Configuration class to create these two bean objects:


@Configuration
@ComponentScan("springinjection")
public class MusicConfig {
    @Autowired Music rawMusic;
    @Autowired Music carnaticMusic;
    @Autowired Piano babyPianoMusic;
    @Autowired Piano pianoMusic;
    @Bean
    public String identifier(@Value("${genre:Generic}") String genre) {
        return genre;
    }
    @Bean(name = "rawMusic")
    @Value("#{genre}")
    public Music createMusic() {
        Music music = new Music();
        return music;
    }
    @Bean(name = "carnaticMusic")
    public Music createCarnaticMusic() {
        Music music = new Music();
        music.setGenre("Carnatic");
        return music;
    }
    @Bean(name = "pianoMusic")
    public Piano createPiano() {
        Piano piano = new Piano(rawMusic, "108");
        return piano;
    }
    @Bean(name = "babyPianoMusic")
    public Piano createBabyPiano() {
        Piano piano = new Piano(carnaticMusic, "88");
        return piano;
    }
}

String object in the Music class

The auto-wired genre property in the Music class is a bit tricky one to Initialize, spring by default treats auto-wired property as required. So when Music class is initialized the container will try to inject a value for the Genre property. But since there is no easy way to inject the String object, We are using the spEL. We will do more about the Spring EL in another post. Now that is all with our configuration file. we will use the following method expression:


@Bean
public String identifier(@Value("${genre:Generic}") String genre) {
        return genre;
}

AppRunner class

  • We will use AnnotationConfigApplicationContext API to inject and run the classes that we created. We will now look at the AppRunner class:

public class MusicRunner {
    public static void main(String args[]) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext("springinjection");
        Piano piano = applicationContext.getBean("pianoMusic", Piano.class);
        Piano babyPiano = applicationContext.getBean("babyPianoMusic", Piano.class);
        Music rawMusic = applicationContext.getBean("rawMusic", Music.class);
        System.out.println("Sathish Music :" + rawMusic);
        System.out.println("Grand Piano :" + piano);
        System.out.println("Baby Piano :" + babyPiano);
    }
}

We inform the container we are using the AnnotationConfigApplicationContext and specifying the package we are using. The other way to initialize the AnnotationConfig is using the class., for example:


ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MusicConfig.class);
        Piano piano = applicationContext.getBean("pianoMusic", Piano.class);
        
        

We have to make sure the MusicConfig class is annotated with @Configuration and the classes that it is annotating is preceding with @Component annotation. One other way to use the AnnotationConfig is to just call the default constructor and register the context at some later point. Let us take look at this sample:


AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.register(MusicConfig.class);
        ctx.refresh();
        Piano piano = applicationContext.getBean("pianoMusic", Piano.class);
        System.out.println("Sathish Music :" + rawMusic);
        
        

We will have to make sure we refresh the context after registering. The same came be done by passing a package as well. If we have an web application we can use the AnnotationConfigWebApplicationContext to configure.

Conclusion

We looked at how to use the AnnotationConfigApplicationContext to configure and run a spring application. With no XML code, spring now allows us to use annotations and configurations to build applications.
Code for this sample can be found in github here