【Spring】学习笔记06 —— 使用注解开发

1. 前提准备工作

在 Spring4 之后,要使用注解开发,必须保证 aop 包导入成功。

在这里插入图片描述

applicationContext,xml 配置文件如下:

<?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

  • singleton:认的,Spring 会采用单例模式创建这个对象。关闭工厂 ,所有的对象都会销毁。
  • prototype:多例模式。关闭工厂,所有的对象不会销毁。内部的垃圾回收机制会回收。

小结

XML 与 注解:

  • XML 可以适用任何场景 ,结构清晰,维护方便;
  • 注解开发简单方便,维护相对复杂;

XML与注解的最佳实践:

  • xml 用来管理 Bean;
  • 注解只负责完成属性的注入;

3. Spring 配置项说明

<context:annotation-config/>的作用是显式地向 Spring 容器注册以下4个BeanPostProcessor,以便容器能够识别相应的注解:

  • AutowiredAnnotationBeanPostProcessor
    • @Autowired
  • CommonAnnotationBeanPostProcessor
  • PersistenceAnnotationBeanPostProcessor
    • @PersistenceContext
  • requiredAnnotationBeanPostProcessor

不过,我们使用注解一般都会配置扫描包路径选项:

<context:component-scan base-package="xxx.xxx"/>

该配置项其实也包含了自动注入上述 processor 的功能,因此当使用 <context:component-scan/>后,就可以将<context:annotation-config/> 移除了。

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念