Spring @autowired annotation – constructor, setter and field injection

The Spring @autowired annotation example shows you how to use the @Autowired annotation to inject a bean with constructor, field or setter method. Here the @Autowired annotation marks a constructor, field or setter method.Then Spring will look up exactly one bean that matches with the property is annotated and autowired automatically.

Create beans
We are using these beans. The Job bean will be autowired in the Person bean. We are showing you three ways you can autowire, via setter, constructor and field injection.

Next, we create Country bean which is autowired into the Fruit bean.

Enabling @Autowired Annotation in Spring configuration
We enable the @Autowired annotation by adding element int the spring configuration file. This will register the AutowiredAnnotationBeanPostProcessor which takes care the processing of annotation.

Now, we together discuss three option Injection method

Option 1: Setter Injection
We can annotate a properties setter method by marking the @Autowired annotation.

Option 2: Constructor Injection

You can have only one constructor with the @Autowired annotation per class. This constructor does not have to be public. When there are multiple constructors with the annotation, a BeanCreationException will be thrown at startup.

Option 3: Field Injection
In Spring, fields are injected right after construction of a bean and set via reflection. This looks a lot simpler than constructor injection or setter injection

Demo Spring application
Create the main class to test the Spring @autowired annotation example

Run the main above, the console will print the following message

Conclusion: As you see above, the field injection looks more simpler than the construction injection and the setter injection. This is reason why I prefer the field injection than others. One more thing for the constructor injection, the constructors become very messy if the class has many dependencies.

That’s all on the Spring @autowired annotation example

Spring @Autowired Doc
@Autowired JavaDoc
AutowiredAnnotationBeanPostProcessor JavaDoc

Download complete source code, click link below

spring-@autowired-annotation-example.zip (304 downloads)

Leave a Comment


Please share it if you found this useful
Hide Buttons