好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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注解的使用解析的详细内容...

  阅读:31次