一、spring简介
Spring框架是由于软件开发的复杂性而创建的。Spring使用的是基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅仅限于服务器端的开发。从简单性、可测试性和松耦合性角度而言,绝大部分Java应用都可以从Spring中受益。作者是Rod Jahnson悉尼大学的音乐学博士。
二、Spring的基本组成

1、spring core:框架的最基础部分,提供 ioc 和依赖注入特性。
2、 spring context:构建于 core 封装包基础上的 context 封装包,提供了一种框架式的对象访问方法。
3、 spring dao:Data Access Object 提供了 JDBC 的抽象层。
4、 spring aop:提供了面向切面的编程实现,让你可以自定义拦截器、切点等。
5、 spring Web:提供了针对 Web 开发的集成特性,例如文件上传,利用servletlisteners 进行 ioc 容器初始化和针对 Web 的 ApplicationContext。
6、 spring Web mvc : spring 中 的 mvc 封 装 包 提供了Web 应用的Model-View-Controller(MVC)的实现。
三、springIOC和DI
3.1 IOC
ioc:Inversionof Control(中文:控制反转)是 spring 的核心,对于spring 框架来说,就是由 spring 来负责控制对象的生命周期和对象间的关系。
简单来说,控制指的是当前对象对内部成员的控制权;控制反转指的是,这种控制权不由当前对象管理了,由其他(类,第三方容器)来管理。

控制权反转:创建对象的权利交给spring容器

3.2 DI
dependence injection “依赖注入”
谁依赖谁? 应用程序依赖spring容器
为什么要依赖? 应用程序需要spring容器来提供对象
谁注入谁? spring容器注入到应用程序
注入了什么? 注入了应用程序需要的对象等资源。
四、项目演示
4.1 创建一个maven项目,引入spring的jar包
<dependencies>
<!-- 引入spring框架-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
演示准备:准备一个学生类、一个老师类
student类
package com.aaa.entity;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
/**
* @author :caicai
* @date :Created in 2022/6/17 14:27
* @description: 学生类
* @modified By:
* @version:
*/
public class Student {
private int id;
private String name;
private Teacher teacher;
private Phone phone;
public Phone getPhone() {
return phone;
}
public void setPhone(Phone phone) {
this.phone = phone;
}
public Student() {
}
public Student(int id, String name, Teacher teacher) {
this.id = id;
this.name = name;
this.teacher = teacher;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public void introduce(){
System.out.println("我的id是:"+this.id+"\t我的名字是:"+this.name+"\t我的老师的id是:"+this.teacher.getId()+"\t我的老师的名字是:"+this.teacher.getName()+"\t我的手机为");
// phone.showInfo();
}
}
teacher类
package com.aaa.entity;
/**
* @author :caicai
* @date :Created in 2022/6/17 14:26
* @description: 老师类
* @modified By:
* @version:
*/
public class Teacher {
private int id;
private String name;
public Teacher() {
}
public Teacher(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
创建一个 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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
</beans>
4.2 spring依赖注入的三种方式
4.2.1 设值注入
设值注入依赖set方法,如果属性没有set方法,注入会失败
在xml配置文件书写下面代码
<!-- 第一种、设置注入:必须依赖set方法 bean中的id是唯一的,name可以不写默认和id的一致 class是要引入的实体类-->
<bean id="teacher" class="com.aaa.entity.Teacher">
<!-- name对应的是实体的属性 value给实体属性赋值(默认调用的是无参构造器)-->
<property name="id" value="1"></property>
<property name="name" value="王老师"></property>
</bean>
<bean id="student" class="com.aaa.entity.Student">
<property name="id" value="1"></property>
<property name="name" value="张三"></property>
<!-- ref是连接获取对应id的属性和属性值-->
<property name="teacher" ref="teacher"></property>
</bean>
在测试类中进行测试
@Test
public void testSpring(){
// 获取spring的容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
// 获取bean 方式一
Student student = (Student) applicationContext.getBean("student");
student.introduce();
// 方式二
Student student1 = applicationContext.getBean("student", Student.class);
student1.introduce();
}
测试结果

4.2.1 构造注入
构造注入依赖构造方法
xml配置文件中书写:
<!-- 第二种:改造注入:依赖的是构造方法-->
<bean id="teacher" class="com.aaa.entity.Teacher">
<constructor-arg index="0" value="2"></constructor-arg>
<constructor-arg index="1" value="李四"></constructor-arg>
</bean>
<bean id="student" class="com.aaa.entity.Student">
<property name="id" value="2"></property>
<property name="name" value="王五"></property>
<property name="teacher" ref="teacher"></property>
</bean>
运行上面的测试代码结果显示

4.2.3 自动注入
一个是 byType 对应的是实体类型(同类型只能对应一个)


执行结果

正常测试

一个是 byName 对应的是实体属性(看和实体类属性的名字是否对应)

测试结果
正常测试

4.2.4 注解方式注入
1、打开注解扫描
<!--注解型 开启组件(bean)扫描 base-package 指定注解扫描的包-->
<context:component-scan base-package="com.aaa"></context:component-scan>
2、使用注解
@Component 该注解标识一个类为springBean,bean的名称/id是类名首字母小写
@Configuration 相当于xml中的 <beans>....</beans>
@Component注解的value 值默认是类名首字母小写,如果手动指定,按照指定的新名字作为bean的id。
@Value() 通常使用在属性上,给属性赋初始化值 !!
对上面测试准备类进行改动
对teacher类加一下注解

对student类中加一下注解

测试结果

五、常见注解
5.1 @Autowired @Qualifier
@Autowired 类似自动注入中的antowire,优先按照类型注入,也可以按照名称注入
@Qualifier (限定符)就是解决依赖注入迷失问题的。
测试 @Qualifier 类
手机接口
@Component
public interface Phone {
void showInfo();
}
安卓手机
@Component
public class AndroidPhone implements Phone{
public void showInfo() {
System.out.println("安卓手机");
}
}
苹果手机
@Component
public class MacPhone implements Phone{
public void showInfo() {
System.out.println("苹果手机");
}
}
学生类注入手机类

没加 @Qualifier 测试结果:结果报错,因为注入 手机接口时有两个现实类具体哪一个没有指明
加 @Qualifier

测试结果:

5.2 @service @controller @repository
- @service 业务逻辑类
- @controller 控制层类
- @repository dao层类

5.3 (" singleton") / ("prototype") @PostConstruct @PreDestroy
@Scope (" singleton") / ("prototype")
singleton 只有一个实例,也即是单例模式。 prototype访问一次创建一个实例,相当于new
spring的bean默认是单例(singleton)的 只有一个实例,也即是单例模式 可以调用
具有prototype作用域的Bean创建后交由调用者负责销毁对象回收资源。
@PostConstruct注解
表示此方法是在Spring实例化该Bean之后马上执行此方法,之后才会去实例化其他Bean,并且一个Bean中@PostConstruct注解的方法可以有多个。
@PreDestroy 注解的方法
如果是单例的时候,@predestroy方法被调用,如果是多例@predestroy这个方法不被调用。
在学生类中添加下面连个方法
@PostConstruct
public void init(){
System.out.println("学生bean初始实例化了");
}
@PreDestroy
public void destroy(){
System.out.println("学生bean被销毁了");
}
一、singleton 测试

编写测试类
@Test // 测试单例和多例对@PreDestroy 注解标记过方法调用情况
public void testScope(){
// 获取spring的容器
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student1 = applicationContext.getBean("student", Student.class);
Student student2 = applicationContext.getBean("student", Student.class);
System.out.println("student1与student2是否为同一对象:"+student1.equals(student2));
student1.introduce();
applicationContext.close();
}
测试结果

二、prototype测试

测试结果

六、配置文件和注解形式的对应关系
6.1 XML 文件的配置
<bean id="" class="" init-method="" destroy-method="" scope="">
<property name="" value=""></property>
<property name="" ref=""></property>
</bean>
-
id:被创建的对象的 id
-
class:要被创建的类对象的类全名
-
init-method:初始化方法
-
destroy-method:销毁方法
-
scope:对象的作用域
-
name:要被注入的数据的名称
-
value:注入数据的值
-
ref:当注入的数据是其他 bean 类型时,其他 bean 类型的名称
6.2 常用注解配置
6.2.1 用于创建对象的注解
注解的作用和 xml 配置文件中编写 <bean></bean> 标签的功能是一样的,即将当前类对象存入 Spring 容器中
1、@component 注解:该注解用于把当前类对象存入 Spring 容器中
value: 指定 bean 的 id。假如我们没有指定 value 的值,默认为当前类名的首字母改小写,其余不变的名称。
2、其中 Spring 还为我们提供了三个作用和 @Component 一样的注解
@Controller 一般用在表现层
@Service 一般用在业务层
@Repository 一般用在持久层
6.2.2 用于改变创建的对象的注入数据的注解
1、@Autowritred 注解:该注解可以自动按照类型注入数据到 bean 中
注入条件:
- 如果 ioc 容器中用唯一的一个 bean 对象类型和要被注入的变量类型匹配
- 如果 ioc 容器中没有对应的 bean 对象类型和要被注入的变量类型匹配,那么会抛出异常。
- 如果 ioc 容器中有多个 bean 对象类型和要被注入的变量类型匹配,首先会根据 id 来匹配,如果 id 都一样,则会根据要被注入的变量的名称匹配,如果变量的名称都一样,那么就会抛出异常。
2、@Qualifier 注解:该注解,在 @Autowritred 的基础之上,可以添加 value 属性值,指定注入的 bean id(需要和 @Autowritred 一起使用)
3、@Resource 该注解和 @Qualifier 类似,可以指定注入的 bean id,但不需要和@Autowritred 一起使用。@Resource 单独使用
4、@Value 注解:该注解用于注入基本数据类型和 String 数据类型
该注解的属性:
value:用于指定数据的值。可以是 Spring 中的 el 表达式(SpEL)
SpEL 书写格式:${EL 表达式}
说明:
@Autowritred@Qualifier@Resource只能注入其他 bean 类型的数据,不能注入基本数据类型和 String 类型的数据。- 集合类型的数据只能通过 XML 文件进行注入。
6.2.3 用于改变创建的对象的作用范围的注解
@Scope 注解:该注解用于指定 Bean 的作用范围
该注解的属性:
value:指定范围的取值。吃常用的取值有:singleton(单例的)、prototype(多例的)
默认为单例的(对象只创建一次)
6.2.4 生命周期相关的注解
@PreDestroy销毁方法的注解@PostConstruct初始化方法的注解
6.2.5 Spring 中的新注解
1、@Configuration 注解
用于指定当前类是一个 Spring 配置类,当创建容器时 会从该类上加载注解。 获取容器时需要使用AnnotationApplicationContext(有@Configuration 注解的类.class)
2、@ComponentScan 注解
用于指定 spring 在初始化容器时要扫描的包。作用和在 spring 的 xml 配置文件中的:
<context:component-scan base-package="pers.stringbug"/> 是一样的
@ComponentScan 注解的属性:
basePackages:用于指定要扫描的包。
value:用于指定要扫描的包。功能和 basePackages 属性功能一样。
3、 @PropertySource 注解
用于加载 .properties 文件中的配置 。 例如我们配置数据源时, 可以把连接数据库的信息写到properties 配置文件中,就可以使用此注解指定 properties 配置文件的位置。
属性:
value[]:用于指定 properties 文件位置。如果是在类路径下,需要写上 classpath:
4、@Bean 注解
该注解只能写在方法上,表明使用此方法创建一个对象,并且放入 spring 容器。
属性:
name:给当前 @Bean 注解方法创建的对象指定一个名称 (即 bean 的 id)。
七、xml配置文件与配置类的对比
配置类:
@Configuration // 标识这是一个配置类 相当之前的xml配置文件 <beans></beans>
@ComponentScan(basePackages = {"com.aaa"}) // 在配置类中扫描包
@PropertySource(value = "classpath:db.properties") // 属性来源
public class MySpringConfig {
@Value("${db.username}")
private String userName;
@Value("${db.password}")
private String password;
@Value("${db.className}")
private String driverClassName;
@Value("${db.url}")
private String url;
@Bean("dataSource")
// 初始化数据源,需要使用db.properties中的四大金刚
public DruidDataSource getDruidDataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUsername(userName);
dataSource.setPassword(password);
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
// dataSource.setUsername("root");
// dataSource.setPassword("root");
// dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
// dataSource.setUrl("jdbc:mysql://localhost:3306/schooldb?useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&allowPublicKeyRetrieval=true");
return dataSource;
}
// bean默认取得是方法名
@Bean
// 初始化jdbcTemplate
public JdbcTemplate jdbcTemplate(){
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(getDruidDataSource());
return jdbcTemplate;
}
@Bean
public UserInfoDaoImpl userInfoDaoImpl(){
// 方式一
// UserInfoDaoImpl userInfoDao = new UserInfoDaoImpl();
// userInfoDao.setJdbcTemplate(jdbcTemplate());
// return userInfoDao;
// 方式二 构造器写法
return new UserInfoDaoImpl(jdbcTemplate());
}
}
配置文件
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<!-- location读取properties文件中的内容 获取四大金刚参数-->
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<!-- 引入德鲁伊jar包————配置数据源参数 德鲁伊参数 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
<property name="driverClassName" value="${db.className}"></property>
</bean>
<!-- 配置jdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="userInfoDaoImpl" class="com.aaa.dao.impl.UserInfoDaoImpl">
<!-- 在dao层注入jdbcTemplate-->
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
对应关系图

1383




被折叠的 条评论
为什么被折叠?



