温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

@Controller,@Service,@Repository,@Component是什么

发布时间:2021-12-14 15:59:21 来源:亿速云 阅读:134 作者:iii 栏目:大数据

本篇内容介绍了“@Controller,@Service,@Repository,@Component是什么”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

@Controller

用来表示一个web控制层bean,如SpringMvc中的控制器。

@Service

用来表示一个业务层bean。

@Repository

用来表示一个持久层bean,即数据访问层DAO组件。

@Component

用来表示一个平常的普通组件,当一个类不合适用以上的注解定义时用这个组件修饰。

@Controller,@Service,@Repository,@Component是什么

需要注意的是@Controller,@Service,@Repository都有带@Component父注解,说明它们除了基本组件的属性外还有其他的的场景应用,即如果不用SpringMVC其实它们就是一个普通的组件,但普通组件建议最好还是用@Component修饰。

@Controller,@Service,@Repository,@Component是什么

为了让Spring自动扫描注册这些组件,需要在配置文件中加上扫描的配置,如扫描com.test包下的注解。

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

些扫描配置默认use-default-filters="true",默认扫描@Component注解及子注解,可以配置过滤只扫描哪些注解不扫描哪些注解。

要过滤扫描注解,需要相应的带上下面的子标签,可以有多个。

<context:include-filter>

<context:exclude-filter>

如只扫描com.test包下的@Controller和@Service注解的组件。

<context:component-scan base-package="com.test" use-default-filters="false">

<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> 

<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/> 

</context:component-scan>

关于type的定义

Filter TypeExamples ExpressionDescription
annotationorg.example.SomeAnnotation符合SomeAnnoation的target class
assignableorg.example.SomeClass指定class或interface的全名
aspectjorg.example..*Service+AspectJ语法
regexorg\.example\.Default.*Regelar Expression
customorg.example.MyTypeFilter自定义Type,实现接口org.springframework.core.type.TypeFilter

另外,<context:component-scan>配置可以有多个。

“@Controller,@Service,@Repository,@Component是什么”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI