Spring Application Configuration using Annotations


This is a series and it would make a lot of sense if read in a sequence. You can find all the posts under the heading “Spring Beginners to Professionals“. In the last post we learnt about Spring XML configurations, specially defining beans in XML using all the bean instantiation methods. In this post, let us try to take one more step and learn the Annotations based configurations.

I have described annotations in one of the previous post.

Spring Application Configuration using Annotations

As I mentioned in earlier posts that configurations can be defined in many ways like XMLs, Java classes or a mix of both. Let us look at an annotation based configuration.  We can define a java class and add the @Configuration annotation on it. The target of this annotation is a Type, which means that the annotation can appear on a class, interface or another annotation class.

We can define a bean inside this class using the @Bean annotation. The target of this annotation is Method and Annotation Types. Which means that the @Bean annotation can appear on methods and annotation classes. So, a bean can be defined by declaring a method as below:

The @Bean annotation accepts a string array for providing bean name and aliases. Now consider the other scenario where the bean is instantiated using a static factory method. Then the configuration shall change to

The OrderClientFactory here is the static factory class and the createOrderClient() method is the static factory method.

And if we want to create the bean using instance factory method then we can define the factory bean first.

After we have created the factory bean, you can inject this bean in the configuration class so that we can use it to invoke the factory method.

What is the @Autowired doing here?

If the @Autowired annotation is used over a field as in this case, Spring finds a bean of the declared type (OrderClientInstanceFactory) and makes it available through the reference variable(instanceFactory).

We will discuss about @Autowired in coming posts.

What next?

Now that we know how to define beans and configurations, the next logical step is to wire these beans together. Here, we used the bean annotation over methods and made the method return an instance of a Java class. Alternatively we can also use @Bean on POJOs directly and let spring create an instance of the class using the no argument constuctor or any other complex instantiation strategy.

In the next post, we will talk about bean collaboration and run our first Spring application. Till then stay connected.