❀ Spring5学习大总结

2022-03-07  本文已影响0人  一乐乐

一、了解 Spring 基本介绍、主要思想 IoC/DI

1、了解 Spring 基本介绍

(1) Spring是什么?

Spring 是一个轻量级DI/IoC 和 AOP 容器开源框架,致力于构建致力于构建轻量级的 JavaEE 应用简化应用开发,本身涵盖了传统应用开发,还拓展到移动端,大数据等领域。

(2) Spring有什么优点?与作用?

① Spring 能帮我们低侵入/低耦合地根据配置文件 创建及组装对象之间的依赖关系。

② Spring 面向切面编程能帮助我们无耦合的实现日志记录,性能统计,安全控制等。

③ Spring 能非常简单的且强大的声明式事务管理(通过配置完成事务,不用修改代码)。

④ Spring 提供了与第三方数据访问框架(如 Hibernate、JPA)无缝集成,且自己也提供了一套 JDBC 模板来方便数据库访问。

⑤ Spring 提供与第三方 Web(如 Struts1/2、JSF)框架 无缝集成,且自己也提供了一套 Spring MVC 框架,来方便 Web 层搭建。

⑥ Spring 能方便的与如 Java Mail、任务调度、缓存框架等技术整合,降低开发难度。


2、主要思想 IoC/DI

Spring 是一个DI容器或IoC容器(DI和IoC 思想差不多)。掌握着创建对象和构建对象之间的依赖控制权

● IoC:Inversion of Control(控制反转):

**一种设计思想**。 其本意是是**将原本在程序中手动创建对象的控制权,交由 Spring 框架来管理**。

● DI:Dependency Injection(依赖注入):

**一种设计思想**。**具体是指 Spring 创建对象的过程中,将对象依赖属性(常量,对象,集合)通过`配置`设值给该对象。**



二、掌握Spring 基本使用、Spring 获取bean对象的方式、Spring 标签 import的引入配置

1、掌握Spring 基本使用

(1) 依赖jar包:

(2) 配置:

(3) 使用:

    @Test
    void testIoC() throws Exception {
        Hello hello = null;
        //=========================
        //1、加载配置文件:从classpath路径去寻找配置文件,创建资源对象
        Resource resource = new ClassPathResource("applicationContext.xml");    
        //2、创建IoC容器:创建spring的工厂对象(IoC容器对象)
        BeanFactory factory = new XmlBeanFactory(resource);
        //3、从Ioc容器获取对象:从spring IoC 容器(就是factory 工厂对象)中获取指定名称的对象
        hello = (Hello)factory.getBean("hello");
        //=========================
        hello.printUser();
    }
■ 从例子,可以看出,spring不仅帮我们创建对象,还帮我们把对象需要的数据给设置进来(对象的属性依赖)


2、Spring 获取bean对象的方式

3、Spring 标签 import的引入配置



三、Spring 核心对象 BeanFactory Bean、Spring的配置方式、了解Spring管理bean的原理

1、Spring 核心对象 BeanFactory Bean

2、Spring的配置方式

■ 元数据的配置有三种方式:

□ XML-based configuration (xml配置文件)

□ Annotation-based configuration (注解

□ Java-based configuration (基于java-config

3、了解Spring管理bean的原理

① 通过 Resource 对象加载配置文件
② 解析配置文件,得到指定名称的 bean
③ 解析 bean 元素,id 作为 bean 的名字,class 用于反射得到 bean 的实例
④ 调用 getBean 方法的时候,从容器中返回对象实例;
■ 结论:就是把代码从 JAVA 文件中转移到了 XML 中。



四、使用Spring的测试框架

相对于传统测试方式,spring测试框架会帮我们关闭对象资源,而使用传统方式,不会正常关闭spring容器。

1、依赖jar包:

2、配置文件:

■ SpringTestTest5-context.xml 文件(文件名必须是测试类-context,因为需要跟测试类名对应上):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
     
    <!-- 配置bean对象 -->
    <bean id="someBean" class="com.shan.spring_test.SomeBean"/>
</beans> 

3、测试类:

■ SpringTestTest5 类:

//SpringTest 案例测试

//运行 Spring JUnit5
@SpringJUnitConfig
public class SpringTestTest5 {
    //表示自动按照类型 Spring容器中去找到bean对象,并设置给该字段
    @Autowired
    private SomeBean bean;
    
    @Test
    void testIoC() throws Exception {
        bean.doWork();
    }
}



五、Spring的核心 IoC(基于xml)

1、ApplicationContext 和 BeanFactory 创建对象的区别

2、常用实例化bean的方式 和 实现FactoryBean接口实例化的方式

(1)实例化bean的方式:

(2)实现FactoryBean接口实例化的方式:


3、 bean作用域scope、初始化init-method和销毁destroy-method

(1) bean作用域scope

<bean id="" class="" scope="作用域"/>

(2) bean初始化和销毁:

<bean id="cat" class="com.shan.lifecycle.Cat" init-method="init" destroy-method="close"/>



六、Spring的核心 DI(基于xml):

{\color{Violet}{ DI跟IoC差不多啦,细节就是DI还负责管理bean对象的属性}}

1、xml配置注入属性值:

配置与注入:


2、bean元素继承 (本质是xml配置内容的拷贝)

图片.png


3、属性注入应用---配置数据库连接池

(1) 配置数据库连接池

    <!-- 配置数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/springdemo?useSSL=false"/>
        <property name="username" value="root"/>
        <property name="password" value="admin"/>
        <property name="initialSize" value="2"/>
    </bean>

(2) db.properties---数据库连接的配置信息

(3) property place holder

● 要是使用标签Context,需要先引入Context的约束(在beans的基础进行修改即可):

图片.png
● context:property-placeholder 属性占位符
     <!-- 从classpath的根路径 加载db.properties -->   
     <context:property-placeholder location="classpath:db.properties"/>
● 使用 ${} 动态引入属性值
    <!-- 配置数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="initialSize" value="${jdbc.initialSize}"/>
    </bean>



七、Spring使用注解配置

1、注解三要素:注解本身、被贴、第三方程序(赋予注解的特殊功能)

★ 对于IoC注解、DI注解:他们的第三方程序是他们对应的解析器。

  • IoC注解:组件扫描器 <context:component-scan base-package=""/>

  • DI注解:注解配置 <context:annotation-config/>

2、DI 注解:@Autowired、@Resource、@Value

(1) 通过注解注入属性值

★ 配置与注入:

(2) IoC 注解:@Component、@Scope、@PostConstruct、@PreDestroy

★ 使用注解@Component(配置Bean)

//相当于 <bean id="dataSource" class="com.shan.ioc.MyDataSource"/>
@Component("dataSource")
public class MyDataSource {

}

★ bean组件版型:

@Component 泛指组件
@Repository 持久层
@Service 业务层
@Controller 控制层

★ 作用域注解、初始化和销毁注解:@Scope、@PostConstruct、@PreDestroy

{\color{Violet}{■ 其中初始化和销毁注解[依赖:javax.annotation-api.jar]}}



八、Spring AOP

1、了解AOP思想[面向切面编程的思想]、AOP思想的原理

(1) 面向切面编程的思想:

利用一种称为"横切"的技术,剖开封装的对象内部,并将那些影响了多个类的公共行为封装到一个可重用模块,并将其命名为"Aspect",即切面。

图片.png

(2) AOP思想的原理:动态代理

2、Pointcot语法

execution(<修饰符>? <返回类型> <声明类型>? <方法名>(<参数>) <异常>)

3、AOP 开发:

(1) 依赖jar包:

(2) 配置:

图片.png
    <!-- AOP 配置:在什么地点、什么时机、做什么 -->
    <!-- 1、what:做什么增强 -->
    <bean id="transactionManager" class="com.shan.tx.TransactionManager"/>
    
    <aop:config proxy-target-class="false"> <!-- 属性proxy-target-class配置是否使用真实对象  -->
        <!-- 配置AOP切面 -->  
        <aop:aspect ref="transactionManager"> <!-- 关联what -->
            <!-- 2、where:在哪些包中的哪些类中的哪些方法上做增强 -->
            <aop:pointcut id="txPoint" expression="execution(* com.shan.service..*Service*.*(..))"/>
            <!-- 3、when:在方法执行的什么时机做增强 --><!-- 关联where -->
            <aop:before method="open" pointcut-ref="txPoint"/>
            <aop:after-returning method="commit" pointcut-ref="txPoint"/>
            <aop:after-throwing method="rollback" pointcut-ref="txPoint"/>
            <aop:after method="close" pointcut-ref="txPoint"/>
            <aop:around method="aroundMethod" pointcut-ref="txPoint"/>  
        </aop:aspect>
    </aop:config>


4、AOP增强的分类

■ 根据被增强的方法的执行时机分为:前置增强、后置增强、异常增强、最终增强、环绕增强


5、获取被增强方法的信息, 并且可以传递给增强方法【参数Joinpoint类

5-2、环绕增强方法调用真实对象的方法【参数processdingJoinpoint

//调用真实对象的方法 ret = pjp.proceed();
public Object aroundMethod(ProceedingJoinPoint pjp) {
        Object ret = null;
        System.out.println("开启事务~");
        try {
            ret = pjp.proceed();//调用真实对象的方法
            System.out.println("调用真实对象的方法...~");
            System.out.println("提交事务~");
        } catch (Throwable e) {
            System.out.println("回滚事务~,错误信息:" + e.getMessage());
        }finally {
            System.out.println("关闭资源~");
        }
        return ret;
    }


6、使用注解配置AOP

(1) AOP注解的解析器【第三方程序,赋予注解的特殊功能】:

<!-- what -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
</bean>
<!-- AOP注解的解析器 -->
<aop:aspectj-autoproxy/>

(2) 使用注解@Aspect配置一个AOP切面

@Component@Aspect //配置一个AOP切面
public class TransactionManager {
    
    //where
    //xml:<aop:pointcut id="txPoint" expression="execution(* com.shan.service..*Service*.*(..))"/>
    @Pointcut("execution(* com.shan.service..*Service*.*(..))")
    public void txPoint() {
        
    }
    
    //@Before("txPoint()")
    public void open(JoinPoint jp) {
        System.out.println("开启事务~");
    }

    //@AfterReturning("txPoint()")
    public void commit() {
        System.out.println("提交事务~");
    }
    //@AfterThrowing(value="txPoint()", throwing="ex")
    public void rollback(Throwable ex) {
        System.out.println("回滚事务~,异常信息:" +ex.getMessage());
    }
    //@After("txPoint()")
    public void close() {
        System.out.println("关闭资源~");
    }
    
    @Around("txPoint()")
    public Object aroundMethod(ProceedingJoinPoint pjp) {
        Object ret = null;
        System.out.println("开启事务~");
        try {
            ret = pjp.proceed();//调用真实对象的方法
            System.out.println("调用真实对象的方法...~");
            System.out.println("提交事务~");
        } catch (Throwable e) {
            System.out.println("回滚事务~,错误信息:" + e.getMessage());
        }finally {
            System.out.println("关闭资源~");
        }
        return ret;
    }
}



九、Spring DAO

1、模板类和基类:

图片.png 图片.png

2、pring JDBC 【JDBCTemplate 模板类】

(1) 依赖jar包:

(2) 总结JdbcTemplate模板类-处理CRUD 操作

//DML操作:
public update(String sql, Object...args)
参数:sql     ?占位符对应的参数
返回:受影响的行数

//DQL 操作:
public <T>List<T> query(String sql, Object...args, RowMapper<T> rowMapper)
参数:sql     ?占位符对应的参数     结果集处理器
返回:多行结果集封装的list

3、模板类JdbcTemplate的问题与解决NameParameterJdbcTemplate

(1) 问题:

● 在模板类JdbcTemplate中使用的占位符 ?【顺序占位符】,需要数第几个,然后写对应的参数,参数多了麻烦
● 面对集合查询 in查询时(不确定参数个数), select * from employee where id in .....

(2) 解决:使用NameParameterJdbcTemplate

□ 举例:

public int countOfActorsByFirstName(String firstName) {
    String sql = "select count(*) from T_ACTOR where first_name = :first_name";
    Map<String, String> namedParameters = Collections.singletonMap("first_name", firstName);
    return this.namedParameterJdbcTemplate.queryForObject(sql, namedParameters,  Integer.class);
}



十、Spring ORM --- 集成mybatis框架



十一、Spring tx

1、Spring 的事务管理主要包括 3 个 api:

✿ 记:常用的事务管理器:

2、事务传播规则 TransactionDefinition 和 常用的情况

(1) 事务传播规则:

在一个事务方法中,调用了其他事务的方法,此时事务该如何传递,按照什么规则传播.

(2) 常用的情况:

■ 情况一:需要尊重/遵从当前事务

■ 情况二:不遵从当前事务的

■ 情况三:寄生事务(外部事务/内部事务/嵌套事务)

3、事务配置(基于xml和注解)

(1) 基于xml:事务增强—本质就是AOP增强what、when、where

    <!-- ===============好比是AOP,事务增强================================== -->
    <!-- 1、what:配置jdbc事务管理器 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!-- 2:when:配置事务管理器增强(环绕增强) --><!-- 关联what -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="trans"/>
        </tx:attributes>
    </tx:advice>
    
    <!-- 3、where:配置切面 --><!-- 关联when -->
    <aop:config>
        <aop:pointcut id="txPc" expression="execution(* com.shan.service.*Service.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPc"/>
    </aop:config>

(2) 使用注解配置jdbc事务:tx注解解析器、@Transactional

(3) 事务配置(基于注解+Java Config 配置)


写在后面的话

       如果你觉得一乐的文章给您带来了一些收获,可以给个三连❤️ ,一乐会一如既往地更新有价值的博客。如果文章存在错误,也欢迎大家指出。还有,如果大家有什么好的学习技巧、学习感悟,也非常欢迎大家在评论区一起交流~

最后感谢大家的支持,谢谢~

上一篇 下一篇

猜你喜欢

热点阅读