Spring中的注解Annotation

Spring标注,在spring2.5版本得到支持,要使用标注,首先得是2.5版本
1 引入 context 命名空间(在 spring的配置文件中)
           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

2 在 spring的配置文件 打开配置,  就可以使用注解处理器了
 <context:annotation-config/>
或者可以用:<context:component-scan base-package="com.sim"/> 
 其中base-package为需要扫描的包(含所有子包)
 
3 引入 注解用的 jar包
lib\j2ee\common-annotations.jar
 
例子:
<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:jee="http://www.springframework.org/schema/jee"
       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/aop
               http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
            http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context-2.5.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.05.xsd" >
    
    <context:component-scan base-package="com.sim"/>
</beans>
标注类中:
@Service用于标注业务层组件,@Controller用于标注控制层组件(如struts中的action),@Repository用于标注数据访问组件,即DAO组件,而@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。 
标注属性、方法 @Autowired和@Resource:
@Autowired 与@Resource 都可以用来装配bean.  都可以写在字段上,或写在set方法上
@Autowired (srping提供的) 默认按类型装配
@Resource ( j2ee提供的 ) 默认按名称装配,当找不到(不写name属性)名称匹配的bean再按类型装配.
可以通过@Resource(name="beanName") 指定被注入的bean的名称, 要是指定了name属性, 就用 字段名 去做name属性值,一般不用写name属性.
@Resource(name="beanName")指定了name属性,按名称注入但没找到bean, 就不会再按类型装配了.
 还有个比较重要的一点是@Resource不是单例的,而@Autowired则是单例的。所以在struts2中使用manager,需要标注时,我个人觉得最好是用@Resource
--------------------------------------------------------------------------------------------------

 
posted @ 2016-07-08 16:55  皈依之路  阅读(140)  评论(0)    收藏  举报