@Autowired vs @Required on setter

0x56794E picture 0x56794E · Sep 19, 2013 · Viewed 33.8k times · Source

I'm curious to know what's the difference between code like this:

class MyClass {
   @Autowired
   MyService myService;
}

and code like this:

class MyClass {
   MyService myService;

   @Required
   public void setMyService(MyService val) {
       this.myService = val;
   }
}

Answer

Sudarshan_SMD picture Sudarshan_SMD · Sep 19, 2013

@Autowired annotation is used when you want to autowire a bean. @Autowired is not limited to setter. It can be used with a constructor and a field as well. If you use @Autowired annotation on a field, that field will be autowired with bean having matching data type.

@Required checks if a particular property has been set or not. If a field has been annotated with @Required annotation and that field is not set, you will get org.springframework.beans.factory.BeanInitializationException.

Refer:

Spring @Autowired usage

Recommended usage of Spring's @Required annotation

Edit: As pointed by 'kryger': field annotated with @Autowired is effectively also @Required (unless you explicitly set its parameter required to false). eg:

@Autowired(required=false)
private ObjectType objectType;

For a field that has been annotated @Autowired, if bean with matching data type in not available, org.springframework.beans.factory.BeanCreationException is thrown.