Tags

, , , ,

In this post I will cover the @Autowired annotation introduced in Spring 2.5.

Three types of @Autowired

The @Autowired annotation can be applied to

  1. On setter methods
  2. On Properties
  3. On Constructors

Beforehand

Do we need a Spring bean configuration file?

The answer is yes and no.

For yes, we do need an xml file.

For no, we do not need to put all bean definitions in this xml file. Just put one line instead (suppose all beans in this sample are located under the com.foo.skill folder)

<context:component-scan base-package=”com.foo.skill” />

This will ask the system to find and register all beans in the application context.

Define our beans (make sure all the beans are located under com.foo.skill)

@Component
public class MyService {
public void printme(){
System.out.println(“printme”);
}
}

Through the annotation @Component, we’ve registered the bean MyService into the application context.

In the “Three types of @Autowired” section we have already known we can put @Autowired in three different places, in the following steps we will demonstrate how to use those three types of @Autowired annotations.

1. field

@Component
public class ExampleService {
@Autowired
private MyService myservice;

public MyService getMyservice() {
return myservice;
}

public String getMessage() {
return “Hello world!”;
}

}

2.setter

@Component
public class ExampleService {
private MyService myservice;

public MyService getMyservice() {
return myservice;
}

@Autowired

public void setMyservice() {
this.myservice=myservice;
}

public String getMessage() {
return “Hello world!”;
}

}

3.constructor

@Component
public class ExampleService {
private MyService final myservice;

@Autowired

ExampleService( MyService service){

super();

myservice=service;

}

public MyService getMyservice() {
return myservice;
}

public String getMessage() {

return “Hello world!”;
}

}

Test it by using SpringJUit4ClassRunner

@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class ExampleConfigurationTests {
@Autowired
private ExampleService service;
@Test
public void testSimpleProperties() throws Exception {
assertNotNull(service);
service.getMyservice().printme();
}
}

Note:

Please be noted, Constructor injection allows you to set the filed to final.

@Autowired on setter is preferable because lack of a setter makes mocking/unit testing more difficult.

Summary 

In this post we saw how to configure the Spring container using the @Autowired annotation. This annotation can be used for on setter methods, on fields, on constructors, with arguments. Examples for the same has been demonstrated.

Advertisements