Annotation based Configuration in spring

This is 15 of 16 parts of tutorial series

Tutorial Content: Spring tutorial for beginners

There are two ways via which you can inject dependency in spring

  1. By configuring XML.
  2. By using annotation.

In all our previous posts,we have injected dependency by configuring XML file but instead of doing this,we can move the bean configuration into the component class itself by using annotations on the relevant class, method, or field declaration.

You might think what if you have done both i.e.used annotations and XML both.In that case,XML configuration will override annotations because XML configuration will be injected after annotations.

Now annotations based configuration is turned off by default so you have to turn it on by entering into spring XML file.

ApplicationContext.xml

Now you are ready to use annotations in your code.Let us discuss few important annotations in spring

@Required:

 The @Required annotation applies to bean property setter methods.

@Autowired:

The @Autowired annotation can apply to bean property setter methods, non-setter methods, constructor and properties.

 @Qualifier:

The @Qualifier annotation along with @Autowired can be used to remove the confusion by specifiying which exact bean will be wired.

 JSR 250 Annotations: 

Spring supports JSR-250 based annotations which include @Resource, @PostConstruct and @PreDestroy annotations.

Was this post helpful?

Comments

  1. awesome tutorial with useful working examples. thx for the great work! I learn Spring solely from these example.

  2. finally i learned the basics of Spring 🙂 in just a day! thanks for this very comprehensive tutorials 🙂 though i was hoping you'd have an example for the annotation based configurations.

Leave a Reply

Your email address will not be published. Required fields are marked *