Spring-Spring Core1 Comment

As I have written in previous posts, you can declare all the beans or components in XML bean configuration file, so that Spring container can detect and register your beans or components.

But more than that, Spring is able to auto scan, detect and instantiate your beans from pre-defined project package, no more tedious beans declaration in in XML file. And most of the time we will use this approach as it bring alot pros.

Let’s see the different between declare components manually and auto components scanning in Spring below.

  • With Declare Manually

CarService : 

CarController : 

And take a look at bean’s configuration file :

spring-core.xml : 

  • With Auto Scanning

For apply auto scanning bean, we will put @Component to class CarService :

CarService : 

and inside CarController, we change to this :

CarController : 

In above code example, you can notice that I also add @Autowire to property carService and remove setter method. To keep in simple, just think about it is a way we injecting a bean, equal to below :

I will explain more about this annotation in another post ( we will using it alot, so it necessary to know deeply about it).

spring-core.xml : 

Put this “context:component” in bean configuration file, it means, enable auto scanning feature in Spring. The base-package is indicate where are your components stored, Spring will scan all this and sub folder and find out the beans (annotated with @Component) and register it in Spring container.

  • Run our Example

Run below code with 2 above examples, you will get same output.

InitClass : 

Output :

  • Auto Components Scan Annotation Types

There are 4 types of auto components scan annotation types

  1. @Component – Indicates a auto scan component.
  2. @Repository – Indicates DAO component in the persistence layer.
  3. @Service – Indicates a Service component in the business layer.
  4. @Controller – Indicates a controller component in the presentation layer.

So, which one to use? It’s really doesn’t matter, they are all same. You can user @Component for all of them or like examples below :

[/crayon]
Service layer

[/crayon]
Controller layer

[/crayon]
Just for good practice, for readability, you should always declare @Repository,@Service or @Controller for a specified layer to make your code more easier to read.

 

 

 


1 Comment on this article

Add a comment