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:

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:

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