Skip to main content

[Spring] Spring IoC & Dependency Injection with Java Annotation

 Last time I've mentioned Inversion of Control and Dependency Injection using XML configuration in Spring. Today we'll be looking at how to do the same configuration using Java Annotations. 


Java annotations are special labels that are added to Java classes/fields/methods that provide meta-data about them. Using annotations minimizes the XML configuration, thus making things less verbose.


Inversion of Control with Java Annotations

First, enable component scanning in the XML config file.

Next, to demonstrate how it works, I'll make an example interface.

I'll also make some classes that implement this. Notice the @Component annotation at the top of the classes. This enables Spring to automatically register the beans when scanning the package. 

Finally, retrieve the beans from the Spring container in the main app.

And the following is the result after running the app.

As the result shows, spring has automatically registered the classes with @Component annotations, and the beans could be retrieved.


Dependency Injection with Java Annotations

Now we go on with injecting dependencies using Java Annotations.
Let's create another interface and an implementing class to be used as a dependency.


Next, we add a new field and a constructor to the classes that were made in the above section, so that they depend on the new interface. Notice the @Autowired annotation - this allows Spring to automatically connect with the parameter by scanning all the components, and autowiring the correct component that implements the interface in the parameter. 


As I have mentioned in my last post, another way to inject dependencies is by using setter methods. @Autowired works in a similar way for the setter method as well. 


Additionally, the most convenient way to inject dependencies is through field injection. This way, constructor/setter methods are not needed. Spring automatically sets the field with the corresponding component - this is done by Java Reflection.


Change the interface accordingly with the newly added methods, and run the main app.



And the dependency is successfully injected automatically.


What if there are multiple components that correspond to the dependent interface? In that case, we need to use @Qualifier to specify the component the class will be depending on.




This was it, now we can configure Spring with minimum XML configuration using Java Annotations.



Comments

Popular posts from this blog

IntelliJ IDEA Error: Cannot determine path to 'tools.jar' library for 17

[Spring] Spring Inversion of Control(IoC) through XML Configuration

[Spring] Spring MVC Configuration - How to set up Spring MVC in IntelliJ