@Controller,@Service,@Repository,@Component详解
轉載自?@Controller,@Service,@Repository,@Component詳解
@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>配置可以有多個。
總結
以上是生活随笔為你收集整理的@Controller,@Service,@Repository,@Component详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java7任务并行执行神器:ForkJo
- 下一篇: 推荐一个在线创作流程图、思维导图软件—P