Bean autowiring using @Autowired annotation

In my tutorial Bean autowiring in Spring framework, I showed to you all three ways to automatically put a dependency object on a dependent object without having to use the ref or list attributes.

In this tutorial, I will introduce you to another way of doing this, which is using @Autowired annotation. Let’s take a look at how to use this annotation!

I still use the example in the tutorial Bean autowiring in Spring framework for example.

Bean autowiring using @Autowired annotation

I will remove autowire=”constructor” in the bean room declaration, now if you run the application again:

You will see the table bean is no longer injected into the room bean.

OK, now we will use @Autowired annotation to bring the table bean into the room bean again.

First, we need to declare @Autowired annotation in the Room class for the variable of the Table object. You can declare:

or

or

To use @Autowired annotation, we need to register the AutowiredAnnotationBeanPostProcessor object with Spring. There are two ways we can do it:

– Use <context: annotation-config />

The <context:annotation-config /> tag is declared to use the appropriate objects related to the annotations declared in the instantiated beans in the Spring container.

In this tutorial, I use the <context: annotation-config /> tag to automatically initialize the AutowiredAnnotationBeanPostProcessor object because we are using the @Autowired annotation.

– Use AutowiredAnnotationBeanPostProcessor directly

Result:

Add Comment