Spring @Configuration Annotation With Examples

Spring @Configuration annotation is part of the spring core framework. Spring Configuration annotation indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application.

Spring @Configuration

Spring @Configuration annotation allows us to use annotations for dependency injection. Let’s understand how to create Spring Configuration classes.

Let’s create a simple java bean class.

Before we use any of the Spring framework classes, we will have to add it’s dependencies to the maven project.

Now let’s create the Spring Configuration class.

Let’s write a simple class and configure our simple Spring configuration class.

If you run above application, it will produce output like this:

Notice that Spring loads beans into it’s context before we have even requested it. This is to make sure all the beans are properly configured and application fail-fast if something goes wrong.

Also ctx.refresh() must be called, otherwise we will get following error when we will try to get any bean from the context.

If you uncomment the statements where I am getting MyBean instances, you will notice that it’s not calling the constructor of MyBean. It’s because the default scope of spring beans is Singleton. We can change it using @Scope annotation.

What if we remove @Configuration annotation?

What will happen if we remove the @Configuration annotation from MyConfiguration class. You will notice that it still works as expected and spring beans are registered and retrieved as singleton classes. But in this case, if we make a call to myBean() method then it will be a plain java method call and we will get a new instance of MyBean and it won’t remain singleton. To prove this point, let’s define another bean that will be using MyBean instance.

Our updated Spring Configuration class is:

Now when we run the MySpringApp class, it generates following output.

So MyBean is not singleton anymore, now let’s annotate MyConfiguration with @Configuration annotation again and run the MySpringApp class. This time output will be like below.

So it’s better to use @Configuration annotation with configuration classes to make sure our spring container is behaving like the way we want it to.

If you don’t want to use @Configuration annotation for some weird reasons, we can still create our configuration class by not calling the myBean() method and rather using an instance variable of MyBean configured through @Autowired annotation. Something like below code will work as well.

That’s all for Spring Configuration annotation, we will look into other spring annotations in future posts.

By admin

Leave a Reply

%d bloggers like this: