@Service代替@Controller注解来标注到控制层的场景?

注解@Override、@Repository、@Service、@Autowired、@Controller、@RequestMapping Override确保方法重写的正确性;@Service实现组件的自动注册和分层标记;@Autowired实现依赖的自动注入,解耦组件关系;定义请求与方法的映射规则,构建 Web 交互流程。理解这些注解的底层逻辑和使用场景,是掌握 Spring 框架的关键。 阅读详情

在SpringBoot开发中,@Controller和@Service基本上是日常开发中使用的最频繁的两个注解。但你有没考虑过@Service代替@Controller注解来标注到控制层的场景?换言之,经过@Service标注的控制层能否实现将用户请求分发到服务层的功能?

前言

在SpringBoot开发中,@Controller注解用于标识一个控制器类,该类负责处理Web请求。而控制器类通常包含若干个方法,每个方法对应一个HTTP请求的处理逻辑。而控制器是MVC(Model-View-Controller)架构的一部分,其主要负责将用户请求分发到适当的服务层,并返回视图或响应数据。而@Service注解用于标识一个服务类,用以负责处理业务逻辑和与数据访问层交互。

相信对于大多数Java开发者来说@Controller和@Service注解的使用都不算太难。但进一步,用@Service标注控制层能否达到和@Controller注解相同的功能呢?对于这个操作你可能会觉得很疯狂,并下意识的说出不可能。但事实果真如此吗?我们不妨先通过一个简单的例子来验证一下。

@Sercice代替@Controller

我们首先自定义一个ServiceController的控制层,其内部通过Autowired注解注入一个UserMapper,并通过userMapper来实现控制层与数据层的交互。具体代码如下:

ServiceController
@Service
@RequestMapping("/ts")
public class ServiceController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping("get-services")
    @ResponseBody
    public User getServices() {
        User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getUsername, "zhangSan"));
        return user;
    }
}

然后,通过PostMan发送一个Get请求,以请求 http://localhost:8080/ts/get-services 其返回内容如下 :

Date: Sun, 21 Jul 2024 02:37:39 GMT
Keep-Alive: timeout=60
Connection: keep-alive

{
  "username": "zhangSan",
  "id": 1,
  "type": null,
  "remark": "test1"
}

通过返回内容,不难看出我们的请求顺利到ServiceController的getServices方法。也就是说我们完全可以用@Service来替代@Controller标注在控制层上!

揭秘背后原理

你可能会觉得@Service来替代@Controller这样的操作有的反常规,因为在学习SpringBoot时,从来也没有那个教程告诉我们@Service注解还有这样的骚操作。那@Service可以这样使用的背后原因到底是什么呢?

众所周知,@Service和@Controller注解都能被Spring容器所加载,并注入到Spring容器中。我们以SpringBoot应用为例来分析其注入容器的全过程。

在分析之前我们首先明确一点,对于Spring而言其会根据配置(如 XML 文件或 @ComponentScan 注解)扫描指定的包及其子包,查找标记有 @Controller、@Service、@Repository 和 @Component 的类。但对于Springboot应用而言,其并没有显示的使用XmL配置或@ComponentScan指定扫描路径的方式来加载对应路径下的Bean信息。

这背后的原因主要在于@SpringBootApplication 注解的使用,@SpringBootApplication其实是一个组合注解,其内部包括以下三个注解:

  • @EnableAutoConfiguration: 启用 Spring Boot 的自动配置机制。

  • @ComponentScan: 启用组件扫描,以便自动发现并注册 Spring 组件。

  • @Configuration: 表示这是一个 Spring 配置类。

在默认情况下,Spring Boot 会从主应用类所在的包开始进行组件扫描,这意味着只要 @Controller 和 @Service 注解的类位于主应用类所在包及其子包中,它们就会被自动发现并注册到 Spring 容器中。

明白了SpringBoot对于Bean的加载逻辑后,我们再来深入到其内部来看。SpringBoot对于这部分Bean的加载流程如图所示:

当我们在main方法中执行SpringApplication.run时,其在run方法内容会完成Spring容器的创建,以及Bean的加载。具体来看,其在AbstractApplicationContext中的invokeBeanPostBeanFactoryPostProcessore时,会通过 ConfigurationClassPostProcessor的 postProcessBeanDefinitionRegistry 方法加载路径下所有的bean名称信息,然后在finshBeanFactoryInitialization完成bean的实例化。而我们绕了这么一大圈就是皆在说明,被@Service,@Controller所标注的类在SpringBoot框架中是如何一步步被注入到容器的。

进一步,笔者曾在揭秘@Controller内部方法与URL绑定的全流程中谈到,对于控制层内的方法,其会在AbstractHandlerMethodMapping中的 afterPropertiesSet()完成请求url与方法的映射绑定。更进一步,afterPropertiesSet的处理逻辑全部委托于于 getCandidateBeanNames和processCandidateBean两个方法。

而getCandidateBeanNames 会获取当前容器中所有的bean 的名称集合,并筛选类中标有@Controller或者 @RequestMapping注解的类交给processCandidateBean处理,以完成请求url与方法的映射。

此时,我们不妨来回看我们一开始的ServiceController的样例代码:

@Service
@RequestMapping("/ts")
public class ServiceController {

   // ....省略内部细节信息
}

不难发现,其虽然没使用@Controller修饰,但其却被@RequestMapping注解信息,也就是说其能被processCandidateBean所处理,进而其也就能完成url和方法映射关系的维护。更进一步,当请求至DispatcherServlet时,SpringMVC变更通过其url信息,找到能处理相应请求的HandlerMethod。从而也就能完成url的处理以及视图的渲染。

事实上,只要你能确保Bean信息注入到容器,并且类信息上至少有@Controller或者 @RequestMapping注解,那便能在AbstractHandlerMethodMapping中所解析,然后完成url与方法的绑定!这也就是为什么我们一开始花费精力研究@Controller 和 @Service 注入容器的原因。

总结

在 SpringBoot 开发中,@Controller 和 @Service 是最常用的注解。通常,@Controller 用于标识控制器类,处理 Web 请求并将请求分发到服务层;而 @Service 用于标识服务类,处理业务逻辑。然而,如果用 @Service 来标注控制层是否可以实现与 @Controller 相同的功能呢?

答案是肯定的。只要类被 @Service 标注,并且包含 @RequestMapping 等注解,Spring Boot 依然能够将其作为控制器来处理请求并返回响应。这背后的原理在于 @Service 和 @Controller 都能被 Spring 容器加载和注册,并且 @RequestMapping 注解能够使类的方法与 URL 映射,从而实现请求处理功能。

90%开发者答错!@Service vs @Controller:Spring Boot控制层的隐藏真相 《Spring Boot核心技术解析:@Controller与@Service的边界与妙用》 本文深入探讨了Spring Boot中@Controller和@Service的异同与灵活应用: 技术验证:通过实验证明@Service标注类在添加@RequestMapping后确实能处理HTTP请求 原理剖析:揭示了Spring组件扫描机制和请求映射的核心逻辑 架构对比:从分层设计角度分析两种注解的适用场景与优劣 应用场景:提出快速原型开发、微服务接口等特殊场景下的合理使用方案 避坑指南:总结开发者常犯的5个典 阅读详情

相关推荐

雷电模拟器+Google Play服务配置全指南:从安装到定位问题解决

本文详细介绍了雷电模拟器配置Google Play服务的全流程,包括版本选择、组件安装、定位服务调试及网络问题排查。针对安卓开发者的常见挑战,提供从基础到高级的解决方案,帮助优化测试环境稳定性与定位精度。

weixin_30399821的博客 1249

Controller层和Service层具体区分

controller层,主要用于给前端返回数据的以及接收前端的数据的, service层,总之就是处理数据用的。 处理controller层传过来的数据然后传给给dao层链接数据库进行增删改查, 从dao层传过来的数据的处理,比如封装成JavaBean。 涉及请求、参数、序列化之类的逻辑可以放在controller。 而具体到数据的操作逻辑,也就是增删改查的操作都应该完整封装到service中。 一方面是对于事务的要求,比如一个请求过来,后台需要多步增删改查,一般都要求放到一个service方法中也就是

demo_yo的博客 1万+

Understand-Anything:AI驱动的代码知识图谱,实现项目全局洞察与高效导航

在软件开发中,理解复杂代码库的结构和依赖关系是提升开发效率的关键。传统代码阅读方式往往陷入局部视角,难以快速把握系统全貌。知识图谱技术通过将代码实体(如文件、类、函数)及其关系(调用、继承、依赖)可视化,为代码理解提供了全局视角。这项技术的核心价值在于将静态代码转化为动态、可交互的认知地图,极大降低了系统学习与维护成本。在实际工程中,它广泛应用于新成员快速入职、遗留系统梳理、架构影响分析等场景。本文介绍的Understand-Anything工具,正是基于这一理念,通过多智能体分析管道,自动构建代码的结构图

weixin_42615290的博客 886

controller和service

做 web 开发,无论哪个语言,无论哪个框架都有 controller 和 service 两个概念,很多时候也分不清楚逻辑写在 controller 还是 service ,框架一般也不做强制限制,都在于开发者自身的素质能力以及对框架的认知。 究竟什么是 controller,可以说他是对 http 中 request 的解析,以及对 response 的封装,它对应的是每一个路由,是 http 请求到代码的一个承接,它必须是可单例的,是无状态的。 service 顾名思义是为了服务而生,为了业务而生,是

qq_33898609的博客 4944

ENVI遥感技术

记录2024.03.06所遇到的遥感问题

qq_44453923的博客 4332

【GAMES101】现代计算机图形学入门 资料整理

课程网址 课程主页 包括ppt 课程PPT和视频 一篇搞定!GAMES101现代计算机图形学入门(全) 作业链接地址 作业论坛 GAMES101课程环境搭建(Win10+VSCode) 计算机图形学笔记 虎书pdf 提取:n2rx 【必须】:高等数学(微积分、线性代数)、算法、数据结构 【非必须】:信号处理、数值分析、大学物理(光学) 在线公式编辑器 一定要做作业,如果个人要配置环境的话应该是配置opencv,eigen这两个核心库就行了,目前觉得最核心的一个作业是作业3,实现着色器和渲染管线,做完一遍

ysh的博客 2685

彻底弄懂@Controller 、@Service、@Component

今天主要聊聊@Controller 、@Service和@Component这三个注解的关系和区别。网上很多人对这三个注解进行了详细的解释,但是仅仅局限于理论,个人对于没有经过自己验证的结果总是持怀疑态度,所有花时间研究了一下,也对这三个注解理解的更加透彻。(ps:网上好多回答不一定正确,所以只能自己花时间验证) 附上三个注解的源代码: @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Indexed

m0_53288098的博客 6175

告别裸机:在FreeRTOS上为STM32移植SOEM 1.4.0的完整指南

本文详细介绍了在FreeRTOS环境下为STM32H7系列芯片移植SOEM 1.4.0的完整指南,涵盖环境准备、任务架构设计、OSAL层适配及网络驱动优化等关键步骤。通过EtherCAT主站解决方案的实现,帮助开发者构建稳定可靠的工业自动化系统,提升实时通信性能。

weixin_33582311的博客 364

controller & service & dao之间的关系

控制层、业务层、数据访问层之间的关系

二哈喇子! 2万+

基于TENG的呼吸测量与识别系统:从蓝牙到WiFi的改造与上位机实现

本文介绍了一种基于摩擦纳米发电机(TENG)的呼吸测量系统改造方案,将原有蓝牙通信升级为WiFi传输。系统通过TENG传感器采集呼吸信号,STM32微控制器处理数据后,经ESP8266 WiFi模块发送至上位机。文中详细阐述了硬件改造(四通道改单通道、蓝牙换WiFi)、嵌入式软件修改(包括ESP8266驱动、数据采集与TCP通信实现)以及上位机软件设计。改造后的系统提升了传输距离和稳定性,为可穿戴健康监测提供了更优解决方案。

huanghm88的专栏 110

【推荐100个unity插件】unity实现交互式火焰 —— Ignis

Ignis是一款Unity互动式消防系统插件,可轻松将物体转换为可燃物。支持固体、植被、蒙皮网格和地形树木等多种对象类型,提供火焰蔓延、熄灭等效果。安装需通过Unity Package Manager添加Visual Effects Graph,并按照指引转换目标物体材质。使用盒型碰撞体或网格计算燃烧区域,可自定义火焰参数和视觉效果。内置多种转换选项,如Flammable Vegetation、Flammable Skinned Mesh等,适用于不同场景需求。注意使用前需备份材质和地形数据,并提供性能优化

向宇的博客,专注php/web全栈 unity游戏开发,欢迎大家评论纠错 2241

SpringMvc三层架构注解详解@Controller、@Service和@Repository

1. @Controller控制层 2. @Service() 3. @Repository持久层 @Autowired依赖注入源码分析 1. @Controller控制层 @Controller用于标记在一个类上,使用它标记的类就是一个SpringMvc Controller对象,分发处理器会扫描使用该注解的类的方法,并检测该方法是否使用了@RequestMapping注解。 @Controller只是定义了一个控制器类,而使用@RequestMapping注解的...

ITSM/ITIL/网络安全/IT运维 1493

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

【SpringBoot】✈️@Service 代替 @Controller 在控制层场景使用

@Service 替代 @Controller 在控制层使用有什么问题

产品经理克星(狗头) 1111

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

Spring注解@Component、@Repository、@Service、@Controller区别

https://blog.youkuaiyun.com/xiao190128/article/details/54890759/   service  是有用的相当于 xml配置中得bean  id = service  也可以不指定 不指定相当于 bean id =  com. service.service 就是这个类的全限定名,表示给当前类命名一个别名,方便注入到其他需要用到的类中;不加的话,默认别名就...

weixin_33940102的博客 6882

深度学习工具包 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")

SpringBoot 控制层中,@Service 可以完全替代 @Controller 吗?

​)架构的一部分,其主要负责将用户请求分发到适当的服务层,并返回视图或响应数据。​​注解用于标识一个控制器类,该类负责处理Web请求。​​时,其在run方法内容会完成Spring容器的创建,以及Bean的加载。​​这样的操作有的反常规,因为在学习SpringBoot时,从来也没有那个教程告诉我们​。​​时,SpringMVC变更通过其url信息,找到能处理相应请求的​。​​内部方法与URL绑定的全流程中谈到,对于控制层内的方法,其会在​。​​ 会获取当前容器中所有的bean 的名称集合,并筛选类中标有​。

kangbin825的专栏 818

SpringBoot控制层中,@Service可以完全替代@Controller吗?

往期热门文章:1、一键生成Java重复代码,摸鱼学新知识!2、美团动态线程池,香啊!3、分布式之一行代码解决缓存击穿问题4、血一般的教训,请慎用 insert into select!5、SpringBoot 引入 liteflow 规则引擎,太香了!作者:毅航来源:juejin.cn/post/7393533304505204787在SpringBoot开发中,@Controller和@Serv...

Java后端技术 138

Spring注解@Repository跟@Service,@Compent,@Controller,@Bean区别及使用场景

今天搬砖的时候,注入bean时在思考该用哪个注解申明,故记录一下 1、@controller 控制器(注入服务) 用于标注控制层,相当于struts中的action层 2、@service 服务(注入dao) 用于标注服务层,主要用来进行业务的逻辑处理 3、@repository(实现dao访问) 用于标注数据访问层,也可以说用于标注数据访问组件,即DAO组件. 4、@component (把普通pojo实例化到spring容器中,相当于配置文件中的 ) 泛指各种组件,就是说当我们的类不属于各种归类的时候(

溪水 3511

Spring注解@Component、@Repository、@Service、@Controller区别 .

Spring 2.5 中除了提供 @Component 注释外,还定义了几个拥有特殊语义的注释,它们分别是:@Repository、@Service 和 @Controller。在目前的 Spring 版本中,这 3 个注释和 @Component 是等效的,但是从注释类的命名上,很容易看出这 3 个注释分别和持久层、业务层和控制层(Web 层)相对应。虽然目前这3 个注释和 @Component...

weixin_34007886的博客 2494

解释@Component @Controller @Service @Repository

@Component大致可以分为以下几个注解 @controller控制器(注入服务),用于标注控制层组件(如struts中的action) @service服务(注入dao),用于标注业务层组件 @repository dao(实现dao访问),用于标注数据访问组件,即DAO组件 @component (把普通pojo实例化到spring容器中,相当于配置文件中的<bea...

我爱编程持之以恒 3331
上一篇: 未来可能消失的9种编程语言...
下一篇: Java七个性能优化手段!
架构文摘JGWZ
博客等级 码龄5年 8808粉丝 345原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值