可以使用注解来代替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注释。
例子见下。