1. 前提准备工作
在 Spring4 之后,要使用注解开发,必须保证 aop 包导入成功。
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="*"/>
</beans>
2. 常见注解使用
Bean
以下4个注解的功能是一样的,都是代表将某个类注册到 Spring 容器中,装配 Bean:
- pojo包:@Compontent
- dao包:@Repository
- service包:@Service
- controller包:@Controller
属性注入
可以在成员变量或者 set 方法上添加 @Value("值")
作用域
@scope
小结
XML 与 注解:
- XML 可以适用任何场景 ,结构清晰,维护方便;
- 注解开发简单方便,维护相对复杂;
XML与注解的最佳实践:
- xml 用来管理 Bean;
- 注解只负责完成属性的注入;
3. Spring 配置项说明
<context:annotation-config/>
的作用是显式地向 Spring 容器注册以下4个BeanPostProcessor,以便容器能够识别相应的注解:
- AutowiredAnnotationBeanPostProcessor
- @Autowired
- CommonAnnotationBeanPostProcessor
- @ Resource
- @ postconstruct
- @ PreDestroy
- PersistenceAnnotationBeanPostProcessor
- @PersistenceContext
- requiredAnnotationBeanPostProcessor
不过,我们使用注解一般都会配置扫描包路径选项:
<context:component-scan base-package="xxx.xxx"/>
该配置项其实也包含了自动注入上述 processor 的功能,因此当使用 <context:component-scan/>
后,就可以将<context:annotation-config/>
移除了。