Spring Autowiring – Setter Injection

Facebooktwitterredditpinterestlinkedinmailby feather

Spring Autowiring – Setter Injection

We have previously discussed an example of Setter Dependency Injection (SDI) using an XML file. In the previous case, we have defined the property name for the dependency injection inside the bean-config file (applicationContext.xml).

Now, we are going to create an example of Setter Dependency Injection (SDI) using @Autowired annotation. With @Autowired annotation, Spring will automatically inject the setter method of the beans.

Example of Auto-wiring using Setter Injection

The Fortune.java and Coach.java are two interfaces that consist of unimplemented methods. The GoodLuckFortune.java and Cricket_Coach.java are the Component classes that implement the Fortune and Coach interfaces, respectively.

Following are the steps to create an example of Autowiring using the Setter Dependency Injection:

Fortune.java

GoodLuckFortune.java

Coach.java

Cricket_Coach

In the above code, we have defined the @Autowired annotation just above the setter method as we are using the Setter Dependency Injection (SDI).

applicationContext.xml

App.java

OUTPUT

applicationContext.xml

Facebooktwitterredditpinterestlinkedinmailby feather