(5) Spring 注解

含义

用于配置依赖对象,与依赖注入平起平坐

 

beans.xml(Spring 配置文件)

<?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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <context:annotation-config/> </beans>

(隐式注册 post-processors 包括了

AutowiredAnnotationBeanPostProcessor,对应着@Autowired

CommonAnnotationBeanPostProcessor,对应着@Resource

PersistenceAnnotationBeanPostProcessorRequiredAnnotationBeanPostProcessor

 

 

在java代码中使用@Autowired或@Resource注解方式进行装配,这两个注解的区别是:

@Autowired 默认按类型装配,也可以使用名称,如: @Autowired @Qualifier("名称")

@Resource默认按名称装配,当找不到与名称匹配的bean才会按类型装配

(在beans.xml中寻找)

 

注意:如果没有指定name属性,并且按照默认的名称仍然找不到依赖对象时, @Resource注解会回退到按类型装配。但一旦指定了name属性,就只能按名称装配了
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:((5) Spring 注解)