gpt4 book ai didi

spring注解@Service注解的使用解析

转载 作者:qq735679552 更新时间:2022-09-29 22:32:09 29 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章spring注解@Service注解的使用解析由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

@Service注解的使用

要说明@Service注解的使用,就得说一下我们经常在spring配置文件applicationContext.xml中看到如下图中的配置:

?
1
2
<!-- 采用扫描 + 注解的方式进行开发 可以提高开发效率,后期维护变的困难了,可读性变差了 -->
< context:component-scan base-package = "com.study.persistent" />

在applicationContext.xml配置文件中加上这一行以后,将自动扫描指定路径下的包,如果一个类带了@Service注解,将自动注册到Spring容器,不需要再在applicationContext.xml配置文件中定义bean了,类似的还包括@Component、@Repository、@Controller.

如这个类:

?
1
2
3
4
5
@Service ( "courseDAO" )
@Scope ( "prototype" )
public class CourseDAOImpl extends HibernateDaoSupport implements CourseDAO{
......
}

其作用就相当于在applicationContext.xml配置文件里配置如下信息:

?
1
2
3
4
< bean id = "courseDAO"
       class = "com.study.persistent.CourseDAOImpl" scope = "prototype" >
       ......   
</ bean >

@Service("serviceName")注解相当于applicationContext.xml配置文件中配置的<bean id="serviceName">,表示给当前类命名一个别名,方便注入到其他需要用到的类中.

@Service注解也可以不指定serviceName,如果不指定相当于<bean id="com.study.service.serviceName">,com.study.service.ServiceName就是这个类的全限定名,不加的话,默认别名就是当前类名,但是首字母小写.

@service注解的简介及使用范例

spring2.5之后出现的注解,就跟在spring配置文件里配置bean差不多的功能,就是让spring自动扫描管理组件,@Service 、@Controller 、@Repository 、@Component ,这四个其实是一样的功能,没有区别,只是在MVC模式上表示的层不一样,service一般标注在service层的bean上,controller标注在控制层,@Repository标注在view层,component通用.

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我.

原文链接:https://blog.csdn.net/jiangyupeng/article/details/84915426 。

最后此篇关于spring注解@Service注解的使用解析的文章就讲到这里了,如果你想了解更多关于spring注解@Service注解的使用解析的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com