可以使用注解來代替xml配置。
@ org.springframework.stereotype.component
一個類若标注了@component,表明此類被作為spring的bean類。對象名預設為類名首字母小寫。也可以@component("name")來手動指定。
此外還有@service、@controller與@repository。它們都有@component的效果,隻是為了友善人看,見名知意。
@org.springframework.stereotype.service
用于标注業務層元件
@org.springframework.stereotype.controller
用于标注控制層元件(如struts中的action)
@org.springframework.stereotype.repository
用于标注資料通路元件,即dao元件
@org.springframework.context.annotation.scope
指定bean的作用域,取值有singleton(預設值)、prototype。可以放在@component注解的上一行。
生成bean的命名規則:
@javax.annotation.resource
spring直接用了java的标準注釋。它與<property />元素的ref屬性有相同的結果。該注解可以放在setter方法前。
@ org.springframework.beans.factory.annotation.autowired
大緻等同于@resource,這是spring自己的。
@inject
大緻等同于@resourcejava,這是依賴注入規範,比@resource要新。
注入bean的命名規則:
有些類是别人寫好的,你沒有機會在這些類的上面添加注解,那就需要用xml來配置了。
<context:annotation-config>
spring預設禁用注解,加上此标簽才能啟用。
它省掉了<propertiy>配置,但省不掉<bean>配置。
<context:component-scan base-package="com.yichudu">
它省掉了<bean>配置。它用來遞歸地掃描這個包及子包下的注解。
一個beans.xml及bean及app代碼示例見下。注意版本号要與jar對應。
過濾元件掃描
可以省略@conponent注釋。
例子見下。