Spring Autowiring –Field Injection

Facebooktwitterredditpinterestlinkedinmailby feather

Spring Autowiring –Field Injection

The Field Injection is used to inject the fields, variables, or properties of the beans. It is not available in autowiring using XML- based configuration. It is a new feature of Spring annotation-based configuration.

The field injection is easy to use in comparison to constructor and setter injection. In the field injection, we don’t need to write any unique code, such as defining constructors or methods.

Example of Autowiring using Field Injection

Here, we are going to create an example of field injection. In this example, there are two interfaces, one is Fortune, and the other is Coach. The GoodLuckFortune and Cricket_Coach are the Component classes that implements the Fortune and Coach interfaces, respectively.

Following are the steps used to create an example of Autowiring using Field injection:

Fortune.java

GoodLuckFortune.java

Coach.java

Cricket_Coach.java

In the above code, we have defined the @Autowired annotation just above the field or parameter of the Cricket_Coach class.

applicationContext.xml

App.java

OUTPUT

Method Injection

The Spring @Autowired annotation provides another type of dependency injection is known as Method Injection. Through method injection, we can inject dependencies by calling any method of the bean class. For example, a method doSomething() is available in the bean, and we can use it for method injection using @Autowired annotation.

For example:

 Cricket_Coach.java

OUTPUT

 Cricket_Coach.java

Facebooktwitterredditpinterestlinkedinmailby feather