Spring Auto scanning components

Normally you declare all the beans or components in XML bean configuration file, so that Spring container can detect and register your beans or components. Actually, 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.
Following is a simple Spring project, including a customer service and dao layer. Let’s explore the different between declare components manually and auto components scanning in Spring.

1. Declares Components Manually

See a normal way to declare a bean in Spring.
Normal bean.

package com.mkyong.customer.dao;
public class CustomerDAO {  
    @Override   
    public String toString() {      
        return "Hello , This is CustomerDAO";   
    }   
}

DAO layer.

package com.mkyong.customer.services;
import com.mkyong.customer.dao.CustomerDAO;
public class CustomerService {  
    CustomerDAO customerDAO;    
    public void setCustomerDAO(CustomerDAO customerDAO) {       
        this.customerDAO = customerDAO; 
    }   
    @Override   
    public String toString() {      
        return "CustomerService [customerDAO=" + customerDAO + "]"; 
    }       
}

Bean configuration file (Spring-Customer.xml), a normal bean configuration in Spring.

<beans xmlns="http://www.springframework.org/schema/beans"  
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
             xsi:schemaLocation="http://www.springframework.org/schema/beans    
                                              http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">        
    <bean id="customerService" class="com.mkyong.customer.services.CustomerService">
        <property name="customerDAO" ref="customerDAO" />   
    </bean> 
    <bean id="customerDAO" class="com.mkyong.customer.dao.CustomerDAO" />
</beans>

Run it

package com.mkyong.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mkyong.customer.services.CustomerService;

public class App { public static void main( String[] args ) {   
    ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});  
    CustomerService cust = (CustomerService)context.getBean("customerService");     
    System.out.println(cust);    
    }
}

output

CustomerService [customerDAO=Hello , This is CustomerDAO]

2. Auto Components Scanning

Now, enable Spring auto component scanning features.
Annotate with @Component to indicate this is class is an auto scan component.

package com.mkyong.customer.dao;
import org.springframework.stereotype.Component;
@Component
public class CustomerDAO {  
    @Override   
    public String toString() {      
        return "Hello , This is CustomerDAO";   
    }   
}

DAO layer, add @Component to indicate this is an auto scan component also.

package com.mkyong.customer.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.mkyong.customer.dao.CustomerDAO;

@Component
public class CustomerService {  
    @Autowired  
    CustomerDAO customerDAO;    
    @Override   
    public String toString() {      
        return "CustomerService [customerDAO=" + customerDAO + "]"; 
    }
}

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 this folder and find out the bean (annotated with @Component) and register it in Spring container.

<beans xmlns="http://www.springframework.org/schema/beans"  
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
            xmlns:context="http://www.springframework.org/schema/context"   
            xsi:schemaLocation="http://www.springframework.org/schema/beans 
                                              http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
                                             http://www.springframework.org/schema/context  
                                             http://www.springframework.org/schema/context/spring-context-2.5.xsd"> 
    <context:component-scan base-package="com.mkyong.customer" />
</beans>

Run it

package com.mkyong.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mkyong.customer.services.CustomerService;

public class App { 
    public static void main( String[] args ) {  
        ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"Spring-AutoScan.xml"});  
        CustomerService cust = (CustomerService)context.getBean("customerService");     
        System.out.println(cust);    
    }
}

output

CustomerService [customerDAO=Hello , This is CustomerDAO]

This is how auto components scanning works in Spring.

Custom auto scan component name

By default, Spring will lower case the first character of the component – from ‘CustomerService’ to ‘customerService’. And you can retrieve this component with name ‘customerService’.

CustomerService cust = (CustomerService)context.getBean("customerService");

To create a custom name for component, you can put custom name like this :

@Service("AAA")
public class CustomerService ...

Now, you can retrieve it with this name ‘AAA’.

CustomerService cust = (CustomerService)context.getBean("AAA");

Auto Components Scan Annotation Types

In Spring 2.5, there are 4 types of auto components scan annotation types

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

So, which one to use? It’s really doesn’t matter. Let see the source code of @Repository,@Service
or @Controller.

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {  
    String value() default "";
}

You will noticed that all @Repository,@Serviceor @Controller are annotated with @Component. So, can we use just @Component for all the components for auto scanning? Yes, you can, and Spring will auto scan all your components with @Component annotated.
It’s working fine, but not a good practice, for readability, you should always declare @Repository,@Service or @Controller for a specified layer to make your code more easier to read, as following :

DAO layer

package com.mkyong.customer.dao;
import org.springframework.stereotype.Repository;
@Repository
public class CustomerDAO {  
    @Override   
    public String toString() {      
        return "Hello , This is CustomerDAO";   
    }   
}

Service layer

package com.mkyong.customer.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mkyong.customer.dao.CustomerDAO;
@Service
public class CustomerService {  
    @Autowired  
    CustomerDAO customerDAO;    
    @Override   
    public String toString() {      
        return "CustomerService [customerDAO=" + customerDAO + "]"; 
    }       
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容

  • Normally you declare all the beans or components in XML b...
    lovePython阅读 397评论 0 2
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,099评论 18 139
  • 写给遥远的自己,写给迷茫的自己。 你有多久没有好好读书了? 你知道吗? 你的气质藏在你走过的路和读过的书里 。 书...
    遇见丁香阅读 564评论 0 1
  • 什么时候成为那个活泼可爱的我? 当听到喜欢的欢快的歌曲的时候? 翩翩的起舞来,踮起脚尖,悠悠的转了转圈;笑容就这样...
    梦想的乐园阅读 124评论 0 1
  • ggvvffffffd
    小牛姑阅读 179评论 0 0