Bean autowiring using @Autowired annotation

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

In this tutorial, I will introduce you 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 the example.

Bean autowiring using @Autowired annotation

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

You will see the bean table no longer beaned in the bean room.

OK, now we will use @Autowired annotation to bring the bean table into the bean room 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 />

<context: annotation-config /> tag is used to dynamically initialize the appropriate objects relate to the annotations that have been declared in the bean to register with Spring container. I will write a post about this tag for you to understand more.

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:

Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment