Spring基本使用

本文详细介绍了Spring框架的核心特性,包括Spring的控制反转(IOC)和面向切面编程(AOP)原理,以及如何配置和使用IOC容器、数据源、注解开发和事务管理。讲解了Bean的生命周期、作用域以及多种装配方式,同时探讨了Spring的动态代理实现和AOP关键概念。此外,还涵盖了Spring JDBCTemplate的基本使用。
一、Spring 框架概述

spring 是分层的JavaSE/EE应用轻量级开源框架,以IOC(inverse of control : 控制反转)和AOP(Aspect Oriented programing: 面向切面 编程)为内核。
在这里插入图片描述

1.2、Spring的优势

1.方便解耦,简化开发

​ 通过spring提供的IOC容器,可以将对象间的依赖关系交由Spring进行控制

2.AOP编程的支持

​ 通过Spring的AOP功能,方便进行面向切面编程。

3.支持声明式事务

4.方便程序的测试

5.方便集成各种优秀的框架

6.降低JavaEE API 的使用难度

Spring 对JavaEE api (jdbc ,javamail,远程调用等),进行了封装,使这些API的使用难度大大降低。

1.3、Spring的体系结构

在这里插入图片描述

1.4 、Spring 的开发步骤

1)、导入坐标

2)、创建bean

3)、创建applicationContext

4)、在配置文件中进行配置

5)、创建ApplicationContext对象getBean

二、IOC容器

实现控制反转的是Spring IOC容器,Spring IOC容器的设计主要基于BeanFactory 和 ApplicationContext两个接口。
在这里插入图片描述

2.1、BeanFactory

2.1.1、该接口提供了完整的IOC 服务支持,是一个管理Bean的工厂,主要负责初始化各种Bean。

注意:使用BeanFactory实例加载Spring配置文件在实际开发中并不多见,了解即可!

2.1.2、ApplicationContext

ApplicationContext是BeanFactory的子接口,也称为应用上下文,除了包含BeanFactory的所有功能外,还添加了对国际化、资源访问、事件传播等内容的支持。

创建ApplicationContext接口实例通常有以下三种方法:

1.通过ClassPathXmlApplicationContext创建(常用):将从类路径目录(src根目录)寻找配置文件

2.通过FileSystemXmlApplicationContext创建:从指定文件的绝对路径寻找配置文件

3.通过Web服务器实例化ApplicationContext容器

4.通过AnnotationConfigApplicationContext

使用注解配置容器对象时,需要使用此类来创建Spring容器,它用来读取注解

2.1.3、getBean()

1.id:存在多个

2.class:存在一个

2.2、依赖注入类型

三种注入类型:

普通数据类型

引用数据类型(对象注入)

集合数据类型

1、使用构造方法注入

2、使用属性的setter方法注入(常用)
在这里插入图片描述

三、Spring 的配置(创建对象、属性注入)
3.1、Bean基本配置

对象交由Spring来创建,默认情况下调用的是类中的无参构造函数,如果没有则不能创建成功。

基本属性:

id:Bean实例在Spring容器中的唯一标识

class:Bean的全限定名称(spring容器利用反射来创建对象)

3.2、Bean的作用域

在这里插入图片描述

singleton(默认): 加载Spring容器(加载配置文件)时,即创建对象,采用的是饿汉式,相同的bean只存在一个。

prototype: 容器中存在多个实例,加载时机为调用即创建,不用不创建。

3.3、Bean的实例化

1.无参构造方法实例化

2.工厂静态方法实例化

3.工厂实例方法实例化

3.4、Bean的生命周期
3.5、Bean的装配方式
四、Spring配置数据源
4.1、数据源(连接池) 的使用

数据源是为了提高性能出现的

事先实例化数据源,初始化部分连接资源

使用连接资源时从数据源中获取

使用完毕后将连接资源归还给数据源

常见的数据源:DBCP、C3P0、Druid等

五、注解开发
5.1 、Spring原始注解

在这里插入图片描述

注意事项:Compoent、Controller、Service、Repository功能相同,只不过可读性高一点

如果按照类型(byType)注入,则只需Autowied;如果想按照id(byName)从容器中进行匹配,则需要Qualifier结合Autowired一起使用。

5.2、新注解

主要应用场景是:对于非自定义的Bean,加载Properties文件,组件扫描,引入其他注解
在这里插入图片描述

用配置类完全代替xml配置(springboot)

六、AOP

AOP(面向切面编程),是通过预编译的方式和运行期**动态代理**实现程序功能的统一维护的一种技术。

作用及优势:在程序运行期间,在不修改源码的情况下进行功能增强,减少重复代码,提高开发效率,并且便于维护。

6.1、AOP的底层实现

AOP底层是通过Spring提供的动态代理技术实现的,在运行期间,Spring通过动态代理技术动态的生成代理对象,再去调用目标对象的方法,从而完成功能的增强。

  1. JDK代理:基于接口的动态代理技术
  2. cglib代理:基于父类的动态代理技术
6.2、AOP的重点概念

Pointcut(切入点):被增强的方法

Advice(通知、增强):封装增强业务逻辑的方法

Aspect(切面):切点+通知

Weaving(织入):将切点与通知结合的过程

**开发明确事项 **:

谁是切点(切点表达式配置)

谁是通知(切面类中的增强方法)

将切点和通知进行织入配置

6.3基于XML的AOP开发

在这里插入图片描述

切点表达式的写法:
在这里插入图片描述

通知的类型:
在这里插入图片描述

6.4、基于注解开发

在这里插入图片描述

七、Spring JDBCTemplate
7.1、开发步骤

1.导入Spring-jdbc和Spring-tx坐标

2.创建数据库表和实体

3.创建JdbcTemplate对象

4.执行数据库操作

7.2、基本使用
package com.codingyoo.dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;

import java.beans.PropertyVetoException;
import java.util.List;
import java.util.Map;

public class JdbcTemplateTest {
    @Test
    public void jdbcTemplateTest01() throws PropertyVetoException {
        //创建数据源对象
        ComboPooledDataSource datasource = new ComboPooledDataSource();
        datasource.setDriverClass("com.mysql.jdbc.Driver");
        datasource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
        datasource.setUser("root");
        datasource.setPassword("root");

        //创建jdbcTemplate对象
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(datasource);

        //执行操作
        List<Map<String, Object>> maps = jdbcTemplate.queryForList("select * from Account");
        System.out.println(maps);
    }

}

Spring代理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:context="http://www.springframework.org/schema/context"
       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">
    <!--加载数据库配置文件-->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
    <!--加载数据源对象-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.Driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!--jdbc模板对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>

测试

package com.codingyoo.dao;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Spring_test {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    public void test01(){
        //更新操作
        jdbcTemplate.update("update account set money = ? where name=?", 100, "lph");
    }
    @Test
    public void test02(){
        //插入操作
         jdbcTemplate.update("insert into account values(?,?)","lisi",200);
    }
    @Test
    public void test03(){
        //删除操作
        jdbcTemplate.update("delete from account where name =?","lisi");
    }
}

八、Spring的事务管理

– 编程式事务管理

​ --基于底层API的编程式事务管理

​ --基于TransactionTemplate的编程式事务管理

– 声明式事务管理

​ --基于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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--加载数据库配置文件-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--加载数据源对象-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.Driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!--jdbc模板对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--为数据源添加事务管理器-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!--编写通知声明事务-->
    <tx:advice id="myAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
    
    <!--编写AOP,让Spring自动对目标对象生成代理,需要使用AspectJ的表达式-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.codingyoo.service.*.*())"/>
        <aop:advisor advice-ref="myAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
</beans>

​ – 基于注解@Transactional的方式

<?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--加载数据库配置文件-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--加载数据源对象-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.Driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!--jdbc模板对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--为数据源添加事务管理器-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!--为事务管理器注册注解驱动器-->
    <tx:annotation-driven transaction-manager="txManager"/>
</beans>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值