@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的定義
另外,context:component-scan配置可以有多個。
推薦去我的博客閱讀更多:
2.Spring MVC、Spring Boot、Spring Cloud 系列教程
3.Maven、Git、Eclipse、Intellij IDEA 系列工具教程
覺得不錯,別忘了點贊+轉發哦!