in Spring

Spring Component scanning and autowiring

Introduction

Component scanning and autowiring are two awesome spring features that automagically create beans and satisfy their dependencies. Component scan in java is configured using @ComponentScan annotation and marking  each bean with @Named or @Component annotation. If you are using xml then you should use

Examples

Java configuration class

@ComponentScan has few options:

  • If you do not specify basePackages component will be scanned in KnightConfigs’s class package
  • To specify multiple packages @ComponentScan(basePackages={"rs.pscode.model","rs.pscode.beans"})
  • Instead of specifying string you can specify class @ComponentScan(basePackageClasses=ModelMarker.class) , spring will scan package of ModelMarker class.

Bean example

To name the bean use  @Component(value="myAwesomeBean")

Autowiring

Every knight needs a good weapon, so lets see the code of a weapon bean.

Now we have a  Weapon to put in the hand of the knight, using @Autowire annotation.

@Autowired can be used in multiple ways

  • with a class property
    @Autowired private Weapon weapon;
  • with a class constructor
  • with a class setter

 

In case spring can not satisfy the dependency automatically it will throw an exception, to avoid this we can use  @Autowired(required = false)

Instead of using @Autowired you can use @Inject too.

Qualifier

What if we have two weapons ?

Lets add another weapon DoubleSword

Now we have two beans that implement Weapon interface and they both qualify. To fix this we will add annotation @Qualifier and specify the name of the bean we want to wire here.

Tests

Lets now test this to make sure that autowiring and component scanning works

 

Component scanning with autowiring is just awesome and easy to use, you should use it when ever you can.

Write a Comment

Comment