Spring自動掃描和裝配bean
1 引入context名稱空間(在Spring的配置檔案中),配置檔案如下:
Xml程式碼- xmlns:context="http://www.springframework.org/schema/context"
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-2.5.xsd
開啟配置 <context:component-scan base-package="包名(掃描本包及子包)"/>
spring 會自動掃描cn.pic包下面有註解的類,完成Bean的裝配。
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
-
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-2.5.xsd">
- <context:component-scan base-package="cn.pic"/>
-
</beans>
2 在classPath中加入註解用的jar包
lib\j2ee\common-annotations.jar
Spring 的context:component-scan掃描支援掃描jar包的方法:
eclipse自帶的jar打包程式,預設打包的時候有個選項<Add directory entries>沒有勾選,只要勾選了,就可以了.
-----------常用註解--------
--定義Bean的註解
@Controller
@Controller("Bean的名稱")
定義控制層Bean,如Action
@Service
@Service("Bean的名稱")
定義業務層Bean
@Repository
@Repository("Bean的名稱")
定義DAO層Bean
@Component
定義Bean, 不好歸類時使用.
--自動裝配Bean (選用一種註解就可以)
@Autowired (Srping提供的)
預設按型別匹配,自動裝配(Srping提供的),可以寫在成員屬性上,或寫在setter方法上
@Autowired(required=true)
一定要找到匹配的Bean,否則拋異常。 預設值就是true
@Autowired
@Qualifier("bean的名字")
按名稱裝配Bean,與@Autowired組合使用,解決按型別匹配找到多個Bean問題。
@Resource JSR-250提供的
預設按名稱裝配,當找不到名稱匹配的bean再按型別裝配.
可以寫在成員屬性上,或寫在setter方法上
可以通過@Resource(name="beanName") 指定被注入的bean的名稱, 要是未指定name屬性, 預設使用成員屬性的變數名,一般不用寫name屬性.
@Resource(name="beanName")指定了name屬性,按名稱注入但沒找到bean, 就不會再按型別裝配了.
@Inject 是JSR-330提供的
按型別裝配,功能比@Autowired少,沒有使用的必要。
--定義Bean的作用域和生命過程
@Scope("prototype")
值有:singleton,prototype,session,request,session,globalSession
@PostConstruct
相當於init-method,使用在方法上,當Bean初始化時執行。
@PreDestroy
相當於destory-method,使用在方法上,當Bean銷燬時執行。
--宣告式事務
@Transactional