@Controller,@Service,@Repository,@Component详解。

@Controller,@Service,@Repository,@Component详解。
原创 javastack Java技术栈 2017-08-03

@Controller

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

@Service

用来表示一个业务层bean。

@Repository

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

@Component

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

需要注意的是@Controller,@Service,@Repository都有带@Component父注解,说明它们除了基本组件的属性外还有其他的的场景应用,即如果不用SpringMVC其实它们就是一个普通的组件,但普通组件建议最好还是用@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 Type Examples Expression Description
annotation org.example.SomeAnnotation 符合SomeAnnoation的target class
assignable org.example.SomeClass 指定class或interface的全名
aspectj org.example…Service+ AspectJ语法
regex org.example.Default.
Regelar Expression
custom org.example.MyTypeFilter 自定义Type,实现接口org.springframework.core.type.TypeFilter

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值