原文地址:http://techidiocy.com/annotation-config-vs-component-scan-spring-core/

<context:annotation-config> and <context:component-scan> are two of the most basic concepts available in the Spring Core introduced in Spring 3 that every Spring user should understand.It is important that to understand the usage of each of them and how they are different to each other.

annotation-config :  Annotation config main job is to activate all the annotations that are present in java beans and those are already registered either by defining in your application context file or being registered while component scanning. Important point is they need to be registered.

component-scan : Component scan can do everything that annotation config does , in addition to it it also registers the java classes as spring bean those are annotated with @Component , @Service ,@Repository etc.

Let’s see an example that can clear the difference in annotation-config vs component-scan in much more simpler way –
I have three java classes that I have declared in my application context.
SuperUser.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.lotusmedia.typesuper;
import com.lotusmedia.typenormal.NormalUser;
import com.lotusmedia.typenormal.TempUser;
public class SuperUser {
    private NormalUser normalUser;
    private TempUser tempUser;
    public SuperUser(){
        System.out.println("Super User Created ->"+this);
    }
    public void setNormalUser(NormalUser normalUser) {
        System.out.println("Setting Normal User ->"+normalUser);
        this.normalUser = normalUser;
    }
    public void setTempUser(TempUser tempUser) {
        System.out.println("Setting Temp User ->"+tempUser);
        this.tempUser = tempUser;
    }
}

NormalUser.java :

1
2
3
4
5
6
7
8
package com.lotusmedia.typenormal;
public class NormalUser {
    public NormalUser(){
        System.out.println("Normal User Created->"+this);
    }
}

TempUser.java :

1
2
3
4
5
6
7
8
package com.lotusmedia.typenormal;
public class TempUser {
    public TempUser(){
        System.out.println("Temporary User Created->"+this);
    }
}

Now here is my application context file where I am injecting normalUser and TempUser into SuperUser.
applicationContext.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 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-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
       ">
 <bean id="normalUser" class="com.lotusmedia.typenormal.NormalUser"></bean>
 <bean id="tempUser" class="com.lotusmedia.typenormal.TempUser"></bean>
 <bean id="superUser" class="com.lotusmedia.typesuper.SuperUser">
    <property name="normalUser" ref="normalUser"></property>
    <property name="tempUser" ref="tempUser"></property>
 </bean>
</beans>

And here is the executor class.
Executor.java :

1
2
3
4
5
6
7
8
9
10
11
package com.lotusmedia.run;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Executor {
    public static void main(String args[]){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    }
}

Now when I executed this program I got output like this in my console and it is what we were expecting.

1
2
3
4
5
Normal User Created->com.lotusmedia.typenormal.NormalUser@75e845c2
Temporary User Created->com.lotusmedia.typenormal.TempUser@1cec6b00
Super User Created ->com.lotusmedia.typesuper.SuperUser@6564dbd5
Setting Normal User ->com.lotusmedia.typenormal.NormalUser@75e845c2
Setting Temp User ->com.lotusmedia.typenormal.TempUser@1cec6b00

Till now everything is good and as expected. Now lets do some modifications and introduce annotations in our beans. So , I have modified SuperUser.java to use annotations for wiring the properties.(notice the autowired annotation).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.lotusmedia.typesuper;
import org.springframework.beans.factory.annotation.Autowired;
import com.lotusmedia.typenormal.NormalUser;
import com.lotusmedia.typenormal.TempUser;
public class SuperUser {
    private NormalUser normalUser;
    private TempUser tempUser;
    public SuperUser(){
        System.out.println("Super User Created ->"+this);
    }
        @Autowired
    public void setNormalUser(NormalUser normalUser) {
        System.out.println("Setting Normal User ->"+normalUser);
        this.normalUser = normalUser;
    }
        @Autowired
    public void setTempUser(TempUser tempUser) {
        System.out.println("Setting Temp User ->"+tempUser);
        this.tempUser = tempUser;
    }
}

And from configuration file I have removed the properties injection, so now my context file looks like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 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-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
       ">
 <bean id="normalUser" class="com.lotusmedia.typenormal.NormalUser"></bean>
 <bean id="tempUser" class="com.lotusmedia.typenormal.TempUser"></bean>
 <bean id="superUser" class="com.lotusmedia.typesuper.SuperUser"></bean>
</beans>

Now I have executed my Executor class again and here is the output.

1
2
3
Normal User Created->com.lotusmedia.typenormal.NormalUser@4cc39a20
Temporary User Created->com.lotusmedia.typenormal.TempUser@485fcf29
Super User Created ->com.lotusmedia.typesuper.SuperUser@a19b1de

This time you will see that properties injection didn’t take place only the new beans were created, now you might be wondering why it didn’t happen as we had marked those properties with the Autowired annotation. So, here is answer , in spring by default annotations don’t do anything by themselves , if you want to use them you have to enable them in your application.
Now enabling annotations in spring is very simple and you have to add only one line of code in your context file to enable them and here is the magic line.

1
<context:annotation-config/>

Updated applicationContext file :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 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-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
       ">
 <context:annotation-config/>
 <bean id="normalUser" class="com.lotusmedia.typenormal.NormalUser"></bean>
 <bean id="tempUser" class="com.lotusmedia.typenormal.TempUser"></bean>
 <bean id="superUser" class="com.lotusmedia.typesuper.SuperUser"></bean>
</beans>

Now this time when I executed the Executor class again , below is the output that I got and this is what we were expecting.

1
2
3
4
5
Normal User Created->com.lotusmedia.typenormal.NormalUser@679bfb30
Temporary User Created->com.lotusmedia.typenormal.TempUser@7977b9b
Super User Created ->com.lotusmedia.typesuper.SuperUser@37fd6bea
Setting Normal User ->com.lotusmedia.typenormal.NormalUser@679bfb30
Setting Temp User ->com.lotusmedia.typenormal.TempUser@7977b9b

So,till now all good, let’s play more now I am going to remove the bean declarations from the Xml file and use @Component annotation to register it as a bean.Here are the updated files.
applicationContext.xml :

1
2
3
4
5
6
7
8
9
10
11
12
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 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-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
       ">
 <context:annotation-config/>
 </beans>

SuperUser.java : (notice the @Component annotation)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.lotusmedia.typesuper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.lotusmedia.typenormal.NormalUser;
import com.lotusmedia.typenormal.TempUser;
@Component
public class SuperUser {
    private NormalUser normalUser;
    private TempUser tempUser;
    public SuperUser(){
        System.out.println("Super User Created ->"+this);
    }
    @Autowired
    public void setNormalUser(NormalUser normalUser) {
        System.out.println("Setting Normal User ->"+normalUser);
        this.normalUser = normalUser;
    }
    @Autowired
    public void setTempUser(TempUser tempUser) {
        System.out.println("Setting Temp User ->"+tempUser);
        this.tempUser = tempUser;
    }
}

NormalUser.java :

1
2
3
4
5
6
7
8
9
10
11
package com.lotusmedia.typenormal;
import org.springframework.stereotype.Component;
@Component
public class NormalUser {
    public NormalUser(){
        System.out.println("Normal User Created->"+this);
    }
}

TempUser.java :

1
2
3
4
5
6
7
8
9
10
11
package com.lotusmedia.typenormal;
import org.springframework.stereotype.Component;
@Component
public class TempUser {
    public TempUser(){
        System.out.println("Temporary User Created->"+this);
    }
}

Now when I executed my Executor class again , this time nothing happened no new bean has been created and no properties has been injected. This is what we were expecting right ? as annotation-config is not suffice and can’t register beans marked with @Component annotation. So , here comes the component scan in play , what it will do , it will scan all the packages provided as an argument to it and will register all the beans marked @Component annotation , and once the bean is registered it annotation-config will inject them.

Now you might be thinking why we need annotation-config when we already have component-scan in our context file ,yes you are thinking in right dierction, as I have already said that component scan can do everything what annotation config does.So, we can safely remove annotation-config from our configuration file and can add component-scan there. So. here is my updated applicationContext file.

1
2
3
4
5
6
7
8
9
10
11
12
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 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-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
       ">
     <context:component-scan base-package="com.lotusmedia.typenormal,com.lotusmedia.typesuper"/> 
</beans>

Now when i executed my Executor class again I got the below mentioned output as we were expecting , all the 3 beans have been created and been injected properly.

1
2
3
4
5
Super User Created ->com.lotusmedia.typesuper.SuperUser@426295eb
Normal User Created->com.lotusmedia.typenormal.NormalUser@207f5580
Setting Normal User ->com.lotusmedia.typenormal.NormalUser@207f5580
Temporary User Created->com.lotusmedia.typenormal.TempUser@4f4db0e3
Setting Temp User ->com.lotusmedia.typenormal.TempUser@4f4db0e3

I hope this example has clarified most of the confusion between annotation-config vs component-scan , if you still have any doubt/question please feel free to drop me a comment, I will be more than happy to answer you.

转载于:https://www.cnblogs.com/davidwang456/p/5645906.html

annotation-config vs component-scan – Spring Core--转相关推荐

  1. Spring教程– Spring Core Framework教程

    Spring is one of the most widely used Java EE frameworks. I have written a lot on Spring Tutorial an ...

  2. Spring Core Container 源码分析七:注册 Bean Definitions

    前言 原本以为,Spring 通过解析 bean 的配置,生成并注册 bean defintions 的过程不太复杂,比较简单,不用单独开辟一篇博文来讲述:但是当在分析前面两个章节有关 @Autowi ...

  3. 【Spring开发】—— Spring Core

    原文:[Spring开发]-- Spring Core 前言 最近由于一些工作的需要,还有自己知识的匮乏再次翻开spring.正好整理了一下相关的知识,弥补了之前对spring的一些错误认知.这一次学 ...

  4. No qualifying bean of type ‘org.apache.rocketmq.spring.core.RocketMQTemplate‘ av

    前言 整合springboot+rocketMq报错 错误信息如下: org.springframework.beans.factory.NoSuchBeanDefinitionException: ...

  5. Java 统计运行时间之 Apache Commons-lang3和Spring Core提供的StopWatch分析

    前言 编码过程中我们经常会希望得到一段代码(一个方法)的执行时间,本文将介绍两种时间监视器(秒表)来让你优雅的.灵活的处理这个问题. Java源生方式 这种方式最最简单,最好理解,当然也是最为常用:我 ...

  6. 在petalinux下提示:Failed to menu config project component....

    现象: 在petalinux下配置硬件描述语言时,提示错误: 命令: petalinux-config --get-hw-description=*.hdf "path" 错误提示 ...

  7. springboot 扫描jar包中bean_详解Spring Boot的Component Scan原理

    本文将帮助您了解Spring中最重要的概念 - 组件扫描.Spring Boot在组件扫描方面做了一些魔术 @ComponentScan 如果你了解组件扫描,你就会理解Spring.Spring是一个 ...

  8. spring core之Ioc介绍

    1.ApplicationContext是BeanFactory的子接口. 2.BeanFactory提供配置框架和基本功能,ApplicationContext添加更多特定于企业的功能. 3.org ...

  9. Spring Core之 Customizing the Nature of a Bean(自定义bean的相关性质)

    文章目录 一.Lifecycle Callbacks (生命周期回调函数) 1.Initialization Callbacks(初始化回调) 2.Destruction Callbacks(销毁回调 ...

  10. spring core源码解读之ASM4用户手册翻译之一asm简介

    第一章:ASM介绍 1.1 ASM动机: 程序的分析,生成,转换技术可以应用到许多场景: 1.程序分析,从简单的语法解析到完整的语义分析,可以应用在程序中找到潜在的bug,发现无用的代码,工程代码的逆 ...

最新文章

  1. dataframe 拆分 分裂
  2. 用python+pygame模块实现一波刮刮卡效果,图像处理之路(附源码)
  3. 如何用一句话证明你是程序员?41 个答案揭晓!
  4. oracle dataguard
  5. 测试稳压二极管特性:BZT52C4V7
  6. Socket编程之简单介绍
  7. Serv-U FTP Jail Break(越权遍历目录、下载任意文件)
  8. python编码在哪里看_python怎么换编码
  9. mt4交易系统源码_如何将源码加载到mt4里面
  10. HTTP中的URL长度限制
  11. 红包大战复盘:谁赢得了这场春节游戏?
  12. Nvivo 12 安装包可自动编码
  13. 台式电脑怎么组装步骤_台式机组装教程,详细教您台式机怎么组装
  14. Java实现腾讯云发送短信
  15. 无人机倾斜摄影测绘工程毕业论文范文
  16. 程序员软考真题__专项:数据结构与算法 02
  17. Flask框架学习笔记(1)
  18. 为什么月薪2万的大数据职位都必须学习Python?
  19. Altium Designer -- EMC/EMI电路设计经验
  20. 攻读博士攻略 攻博贴士

热门文章

  1. lisp 河道水面线计算_水面漂浮泡沫生活垃圾隔离拦载浮筒使用方法
  2. 知识图谱前端插件_大型前端项目可持续演进开发的思考
  3. excel 两组数据交点_30秒即可完成Excel数据对比,超高效率,快学起来不要犹豫!...
  4. cumsum在matlab中,matlab中cumsum函数和sum函数详解
  5. pyqt 获取 UI 中组件_初级UI需注意10个移动端的关键原则
  6. 怎么把本地的文件传给服务器,怎么把本地文件传给云服务器
  7. acid php5,ACID原则
  8. java+queue+se_「013期」JavaSE面试题(十三):多线程(3)
  9. android android:process=,Android app启动流程
  10. linux常见系统目录,Linux系统中常见目录有哪些?linux运维学习中心