Spring的组件自动扫描机制

Spring扫描器—spring组件扫描使用详解 NULL 博文链接:https://gaozzsoft.iteye.com/blog/1523898 立即下载

来源:http://blog.163.com/qqabc20082006@126/blog/static/2292852520091128103316534/ 


Spring的组件自动扫描机制  

Spring将所有的bean都纳入到IOC中创建、管理和维护。对于大型的项目而言,项目中会有成百上千个bean,如果我们都在配置文件中配置,那么我们就会增加配置文件的体积,显得过于臃肿,过于庞大,查找维护起来也不太方便。

在Spring2.5中引入了组件自动扫描机制,通过在classpath自动扫描的方式把组件纳入到Spring容器中。这大大减少了程序员在配置XML文件上的时间,使得配置文件显得干净,整洁,便于维护。

这种机制的工作步骤是:

1.配置需要扫描的类;

2.在需要被纳入Spring容器的类上加上相应的注解;

3.Spring在类路径下寻找标注了注解的类,并把这些类纳入Spring容器中管理。

它的作用是和在XML文件中使用<bean>节点配置组件是一样的。

自动扫描组件的使用

第一步:配置applicationContext.xml文件;如下:

<?xml version="1.0" encoding="UTF-8"?>

<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"

xmlns:p="http://www.springframework.org/schema/p"

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

">

<!-- 打开Spring组件自动扫面,并配置要扫描的基本包 -->

<context:component-scan base-package="com.springtest"></context:component-scan>

</beans>

注:<context:component-scan>节点用于通知Spring容器扫描组件,base-package属性用于指定将要被扫描的组件所在的包名称。

第二步:为需要被扫描的类添加相应的注解;注解的类型有以下几种:

· @Service 用于标注业务层组件;

· @Repository 用于标注数据访问层组件;

· @Controller 用于标注控制层组件(如:Struts中的action)

· @Component 表示泛型组件,当组件不好归类的时候,我们可以使用这个组件进行注解。

第三步:当为类添加完成注解后,我们需要测试相应的组件是否被纳入Spring容器,所以我们需要测试组件是否被扫描;如下:

@Test

public void testAddUser()

{

UserBiz userBiz = (UserBiz)context.getBean("userBizImpl");

System.out.println(userBiz);

}

如果输出不为空,则说明测试类已经被扫描并且纳入了Spring容器。

细节问题总结:

1.当我们进行测试时,用ApplicationContext对象的getBean()方法寻找组件。在之前的配置文件中我们会用<bean>标签的id属性去定义,在使用注解后怎样获得组建的id呢?

在这种情况下,Spring会将被标注注解的类名拿到,然后再将该类名的第一个字母变为小写,放到getBean()方法中。如:UserBizImpl类的组件Id就会是userBizImpl,获取时为context.getBean("userBizImpl");

那么,我们在使用注解时可以自定义组件的Id吗?

当然可以。我们需要在为相应的类添加注解时,在注解之后添加自定义的类名,例如:

@Service("userBiz")

public class UserBizImpl implements UserBiz {

……

}

当我们在获取该组件时,为context.getBean("userBiz);

2.在配置文件中我们可以对组件(bean)的作用域范围进行设置,它的默认值是单例模式,那么在添加注解的情况下,我们怎样设置组件的作用域范围呢?

我们可以直接在为类添加注解的同时,运用另一个注解@Scope("prototype")来设置,如下

@Service("userBiz")@Scope("prototype")

public class UserBizImpl implements UserBiz {

……

}

3.在使用注解时,为组件设置初始化和销毁方法:

在添加注解的相应的类中,如果想初始化或销毁某个方法,我们可以直接在方法上添加注解,如下:

@PostConstruct

public void addItem() {

System.out.println("初始化方法");

}

@PreDestroy

public void testItem() {

System.out.println("释放资源");

}

4.在使用Spring自动扫描组件后,怎样进行依赖注入?

运用注解@Resource和@Autowired,并为依赖对象设置名称,例如:

@Resource(name="userDao")

private UserDAO userDao = null;

首先它会根据名称去找Spring自动扫描的并加入到Spring容器的组件(bean),如果有相同的名称,则进行依赖注入,如果没有相同的名称。则会根据类型区寻找组件。

<context:component-scan base-package="com.mycompany">

   <context:include-filter type="regex" expression="com\..mycompany\..service\...*" />

   <context:exclude-filter type="aspectj" expression="com.mycompany.util..*" />

</context:component-scan>

当有<context:component-scan />后,就可以将<context:annotaion-config />移除了。

Spring自动装配与扫描注解代码详解 主要介绍了Spring自动装配与扫描注解代码详解,具有一定借鉴价值,需要的朋友可以参考下。 立即下载

相关推荐

基于Flink的风控系统

可以使用Flink-Stream进行实时数据流的检测和处理,或者使用Flink-Kafka集群进行数据转发和存储,然后使用Flink-Table进行数据表的查询和分析。在Flink中,可以使用Flink-Stream进行数据流的处理,或者使用Flink-Kafka进行Kafka数据流的消费和处理。Flink的运行时本身也支持迭代算法的执行。可以使用Flink-Stream进行实时数据流的检测和处理,或者使用Flink-Kafka集群进行数据转发和存储,然后使用Flink-Table进行数据表的查询和分析。

m0_68231587的博客 1875

spring自动扫描机制

         记得之前的项目中leader曾经要求我自己写一个类似spring的自动代码扫描器以便扫描我们代码中一些自定义的method,annotation或者注释方式,并且我们要对扫描结果做自己的处理。                   这就促使我去看spring中是如何自动扫描的,按照我的认识,应该不外乎2种方法。一是装载配置的根路径及其子文件夹下所有的类文件,并且根据每个被装载的文件...

笨狐狸 6591

手机摄影新宠:In-line Hardware EIS如何让你的4K视频稳如鸡头(附实测对比)

本文深入解析了手机摄影中的In-line Hardware EIS(硬件级行内电子图像稳定)技术。通过对比传统软件EIS,阐述了其通过硬件管道实时处理实现极低延迟、减少画面裁切和有效抑制果冻效应的核心优势,并结合4K视频的日夜间实测,展示了该技术如何让手持拍摄的视频“稳如鸡头”,显著提升创作体验与成片质量。

tree的博客 998

spring 组件 扫描

@ComponentScan(basePackages = {“com”}) 组件扫描 @ComponentScan等价于 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.scan("com"); 模拟包扫描 获取项目真实路径 File file =new File(RealPath) String[] files= file.list() clazz = fi

qq_44745938的博客 599

Moveit +Gazebo:搭建单臂机械臂仿真平台

Moveit +Gazebo:搭建单臂机械臂仿真平台

magic_invaid的博客 5294

MNIST数据集下载+idx3-ubyte解析【超详细+上手简单】

下载MNIST数据集并对其进行图片与标签解析

qq_43604183的博客 3万+

spring(六)--------spring的扫描机制

我们说到这个实现类完成对注解类的扫描。可以看到只获取includeFilters中存在的,我们知道我们自己在配置类的@CompnentScan注解中手动加入了一个Scan_C类到includeFilters,所以Scan_C是可以扫到的,那么加了@Compnent注解的Scan_A又是怎么被扫描的?-----》如是则获取配置类的部分属性,实例化一个扫描器(扫描器实例化的时候会将Compnent类加入到includeFilters中,为了后判断哪些类用了@Compnent注解)

qq_35599414的博客 2258

步进电机原理及梯形加速算法

步进电机重理解与梯形加速算法

weixin_39912966的博客 1324

Spring注解扫描:ComponentScan使用及原理详解

当下约定大于配置和Spring提供的基于注解配置式开发,解决了繁琐的XML文件配置问题,大大提高了开发效率。基于Spring MVC三层架构框架开发的项目中大量用到等注解,即使这些类在不同包路径下,都能被注入到Spring容器中,然后可以相互之间进行依赖注入、使用。Spring是如何将声明了@Component注解的Bean注入到Spring容器当中的呢?怎么做到bean的类定义可以随意写在不同包路径下?答案就是今天的主角,该注解告诉Spring扫描那些包路径下的类,然后判断如果类使用了等注解,就注入到。

weixin_41821642的博客 7466

3.7 改造模型:为GPT添加一个分类头(Classification Head)

本文介绍如何改造GPT模型用于文本分类任务。主要内容包括: 分类头设计思路:GPT作为语言模型需要添加分类头才能适应分类任务,类似于为语言大师添加裁判功能。 序列表示选择策略: 分析三种常见方法(CLS标记、平均池化、最后词元表示) 推荐使用最后词元表示,因其最能反映GPT的单向信息流特性 代码实现: 构建GPT2ForSequenceClassification类 包含预训练GPT主体和线性分类头 使用attention_mask智能定位句子结尾 通过高级索引提取最后词元特征 该方法通过简单改造使GPT模

yonggeit的博客 2973

【异常检测】【EfficientAD】论文简单梳理与代码实现

EfficientAD作为较近的一篇异常检测网络,主要还是从S-T网络入手,对齐进行了相关改进。修改特征提取器引入自动编码器hard loss以及惩罚项。

胡侃有料的博客 2860

Spring 的组件自动扫描机制

Spring将所有的bean都纳入到IOC中创建、管理和维护。对于大型的项目而言,项目中会有成百上千个bean,如果我们都在配置文件中配置,那么我们就会增加配置文件的体积,显得过于臃肿,过于庞大,查找维护起来也不太方便。 在Spring2.5中引入了组件自动扫描机制,通过在classpath自动扫描的方式把组件纳入到Spring容器中。这大大减少了程序员在配置XML文件上的时间,使得配置文件

Bolin 876

3、图像中文字信息提取技术全解析

本文全面解析了图像中文字信息提取(Text Information Extraction,TIE)的技术原理、挑战及应用领域。详细介绍了图像中三种主要文字形式:场景文字、字幕文字和文档文字的特点及提取难点。系统阐述了TIE技术的主要流程步骤,包括文字检测、定位、提取与增强、识别等关键阶段,并对主流技术方法进行了分类比较,包括基于连通组件、边缘、纹理等方法的优缺点分析。文章还介绍了多种其他提取技术,如二值化方法、混合方法、基于梯度的方法等,并提出了一种基于立体帧的新型场景文字提取方法,通过实验验证了该方法在召

ll5678的博客 119

Spring_5_组件自动扫描机制

Web.xml的配置、PersonDao类、PersonDao类与1中相同。 自动扫描机制就是,它可以在类路径下寻找标注了@Component、@Service、@Controller、@Repository注解的类,并把这些类纳入Spring容器中管理。 1)PersonDaoBean 类: @Repository public class PersonDaoBean implements

阿_顺u012963457的专栏 955

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

java自动扫描,Spring_5_组件自动扫描机制

Spring_5_组件自动扫描机制Web.xml的配置、PersonDao类、PersonDao类与1中相同。自动扫描机制就是,它可以在类路径下寻找标注了@Component、@Service、@Controller、@Repository注解的类,并把这些类纳入Spring容器中管理。1)PersonDaoBean 类:@Repositorypublic class PersonDaoBean ...

weixin_35849560的博客 182

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

从0到1掌握mini-spring包扫描机制:解决Spring组件自动发现的核心痛点

你是否还在手动配置每一个Spring Bean?当项目规模超过50个组件时,XML配置文件的维护成本会呈指数级增长。据Spring官方统计,采用包扫描(Package Scanning)机制可减少70%的配置代码,同时降低40%的配置错误率。本文将通过mini-spring框架的PackageScanTest实例,深入剖析Spring IoC容器如何实现组件的自动发现与注册,让你彻底理解从注解解析...

gitblog_00039的博客 1062

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

spring2.5提供的组件自动扫描机制

在spring2.5以后的版本都为我们提供了组件自动扫描机制,大大方便了我们这新程序员啊,它可以在类路径下寻找标注了 ----      @Component,@Service,@Controller,@Repository注解的类,并把这些类纳入进spring容器中管理。下面写这个是引入component的扫描组件   其中base-package为需要扫描的包(含所有子包)

tx_rain的专栏 355

自动扫描方式把组件纳入spring容器中管理

spring2.5引入了组件自动扫描机制, 他可以在类路径底下寻找标注了 @Component、@Service、@Controller、@Repository注解的类, 并把这些类纳入进spring容器中管理。 @Service用于标注业务层组件、 @Controller用于标注控制层组件(如struts中的action)、 @Repository用于标注数据访问组件

dwt1220 748
上一篇: oracle使用cursor动态更新线上初始化数据
下一篇: HTML5 元素拖拽 移动删除效果
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值