在使用Spring的過程中,為了避免大量使用Bean注入的Xml配置文件,我們會采用Spring提供的自動掃描注入的方式,只需要添加幾行自動注入的的配置,便可以完成
Service層,Controller層等等的注入配置.使用過程中,在Service層中的實現類頭上加@Compopnet注解,在Controller類頭加@Controller注解,便完成了配置。例如在
Controller中當我們調用某個Service時就不需要Set方法了,直接通過@Autowried 注解對Service對象進行注解即可:例如
在Controller中:
@Controller
@RequestMapping("/test") public class ExampleController { @Autowired private ExampleService service; }
在Service中
@Component public class ExampleServiceImpl Implements ExampleService { @Autowired private ExampleDao exampleDao; }
Spring 中的XML配置:
<!-- 自動掃描service,controller組件 --> <context:component-scan base-package="com.example.service.*"/> <context:component-scan base-package="com.example.controller.*"/>
通常,在Bean為添加@Component注解的情況下,在啟動服務時,服務會提前報出以下代碼中這樣的異常情況下,此時應該檢查相應Bean是否正確添加@Component
注解,而在Controller層中未配置@Controller的情況,啟動時服務可能不會爆出異常,但是你會發現頁面請求中的URL地址是正確的,當時無論如何也訪問不到Controller中相
對應的方法,這個時候就需要那么需要檢查@Controller注解和@RequestMapping注解是否已經添加到Class上面了。
org.springframework.beans.factory.BeanCreationException:Error creating bean with name 'example' No matching bean of type [com.example.ExampleService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
下面就詳細介紹下@Component,@Controller注解:
- org.springframework.stereotype.Component (implements java.lang.annotation.Annotation)
在自動服務,spring初始化的時候,spring會把所有添加@Component注解的類作為使用自動掃描注入配置路徑下的備選對象,同時在初始化spring@Autowired
注解相應的Bean時,@Autowired標簽會自動尋找相應的備選對象完成對bean的注入工作。
- org.springframework.stereotype.Controller (implements java.lang.annotation.Annotation)
@Controller注解是一個特殊的Component,它允許了實現類可以通過掃描類配置路徑的方式完成自動注入,通常@Controller是結合@RequestMapping注解一起使用的。
結語:
通過了解Spring的注解可以幫助我們在使用Spring開發過程中提高開發效率,同時也加強了我們對Spring的認識。在使用Spring開發的過程中,我個人更傾向於使用注解的方式,減少配置文件代碼。