1.注解的方式配置Bean(重点)
1.1 基于注解配置 Bean(原理:组件扫描,Spring 能够从 classpath 下自动扫描, 侦测和实例化具有特定注解的组件)
1.1.1 特定组件
@Component: 基本注解, 标识了一个受 Spring 管理的组件
@Respository: 标识持久层组件
@Service: 标识服务层(业务层)组件
@Controller: 标识表现层组件
1.1.2 配置与jar包
(1) 新增两个jar包:spring-aop-5.1.8.RELEASE.jar spring-aspects-5.1.8.RELEASE.jar
(2) 头文件导入完整
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
1.1.3 基本流程
(1) 在bean前添加特定注解
(2) 在xml文件中配置 <context:component-scan base-package="需要扫描的包名"/>
base-package 属性指定一个需要扫描的基类包
resource-pattern 属性过滤特定的类
bean
@org.springframework.stereotype.Repository("repository")
public class Repository {
public void save(){
System.out.println("This is Repository...");
}
}
annotation.xml
<context:component-scan base-package="annotation"/>
1.1.4 扫描组件的context
(1) <context:component-scan>
(2) <context:include-filter> 子节点表示要包含的目标类
(3) <context:exclude-filter> 子节点表示要排除在外的目标类
1.1.5 <context:include-filter>
和 <context:exclude-filter>
子节点支持多种类型的过滤表达式
1.2 基于注解来装配 Bean 的属性
1.2.1 组件装配的注解类型
(1) @Autowired 注解自动装配具有兼容类型的单个 Bean属性
(2) @Resource 注解要求提供一个 Bean 名称的属性
(3) @Inject 按类型匹配注入的 Bean, 但没有 reqired 属性
1.2.2 @Autowired
(1) 构造器, 普通字段(即使是非 public), 一切具有参数的方法都可以应用@Authwired 注解
(2) 所有使用 @Authwired 注解的属性都需要被设置. 若某一属性允许不被设置, 可以设置 @Authwired 注解的 required 属性为 false
(3) 当 IOC 容器里存在多个类型兼容的 Bean 时, 通过类型的自动装配将无法工作. 此时可以在 @Qualifier 注解里提供 Bean 的名称
1.2.3 基本流程
controller的save方法 调用 service的save方法,service的save方法调用repository的save方法
controller
@org.springframework.stereotype.Controller
public class Controller {
@Autowired
private Service service;
public void save(){
System.out.println("This is Controller...");
service.save();
}
}
service
@org.springframework.stereotype.Service
public class Service {
@Autowired
private Repository repository;
public void save(){
System.out.println("This is Service...");
repository.save();
}
}
repository
@org.springframework.stereotype.Repository("repository")
public class Repository {
public void save(){
System.out.println("This is Repository...");
}
}
2.Spring的新特性
2.1 泛型依赖注入(父类之间的依赖关系,相应子类之间自动注入依赖关系)
Spring 4.x 中可以为子类注入子类对应的泛型类型的成员变量的引用
2.2 整合多个配置文件
(1) Spring 允许通过 <import> 将多个配置文件引入到一个文件中,进行配置文件的集成。
(2) import 元素的 resource 属性支持 Spring 的标准的路径资源