@Controller,@Service,@Repository,@Component详解
轉(zhuǎn)載自?@Controller,@Service,@Repository,@Component詳解
@Controller
 
 
用來(lái)表示一個(gè)web控制層bean,如SpringMvc中的控制器。
 
 
@Service
 
 
用來(lái)表示一個(gè)業(yè)務(wù)層bean。
 
 
@Repository
 
 
用來(lái)表示一個(gè)持久層bean,即數(shù)據(jù)訪問(wèn)層DAO組件。
 
 
@Component
 
 
用來(lái)表示一個(gè)平常的普通組件,當(dāng)一個(gè)類不合適用以上的注解定義時(shí)用這個(gè)組件修飾。
 
 
 
 
 
 
需要注意的是@Controller,@Service,@Repository都有帶@Component父注解,說(shuō)明它們除了基本組件的屬性外還有其他的的場(chǎng)景應(yīng)用,即如果不用SpringMVC其實(shí)它們就是一個(gè)普通的組件,但普通組件建議最好還是用@Component修飾。
 
 
 
 
為了讓Spring自動(dòng)掃描注冊(cè)這些組件,需要在配置文件中加上掃描的配置,如掃描com.test包下的注解。
 
 
<context:component-scan base-package="com.test" />
 
 
些掃描配置默認(rèn)use-default-filters="true",默認(rèn)掃描@Component注解及子注解,可以配置過(guò)濾只掃描哪些注解不掃描哪些注解。
 
 
要過(guò)濾掃描注解,需要相應(yīng)的帶上下面的子標(biāo)簽,可以有多個(gè)。
 
 
<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>
 
 
關(guān)于type的定義
 
 
| Filter Type | Examples Expression | Description | 
| annotation | org.example.SomeAnnotation | 符合SomeAnnoation的target class | 
| assignable | org.example.SomeClass | 指定class或interface的全名 | 
| aspectj | org.example..*Service+ | AspectJ語(yǔ)法 | 
| regex | org\.example\.Default.* | Regelar Expression | 
| custom | org.example.MyTypeFilter | 自定義Type,實(shí)現(xiàn)接口org.springframework.core.type.TypeFilter | 
 
 
另外,<context:component-scan>配置可以有多個(gè)。
總結(jié)
以上是生活随笔為你收集整理的@Controller,@Service,@Repository,@Component详解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
 
                            
                        - 上一篇: Java7任务并行执行神器:ForkJo
- 下一篇: SiteGround vs DreamH
