Spring课堂笔记

前言

本人刚开始工作,空闲之余重新学习一下spring,有了些新理解,便写了此篇博客记录一下,希望能对跟我一样刚入行的朋友有帮助。
Sping两个核心概念:IOC和AOP,接下来我会谈一谈我对这两者及其相关知识点的理解。理解有偏差之处,恳请各位前辈的指教。^ ^
ps:学习视频为B站狂神说Java的Spring教程,CSDN账号为“狂神说”
【 】中的为相关知识点的理解,可跳过。

IOC:Inversion of Control,控制反转

IOC是一种思想,它的一种具体实现方式是DI,即依赖注入。

一、为什么要引入IOC这种思想呢
假如用最原始的方法写三层架构,那么写代码的步骤为:
目录结构
1.创建dao接口,接口中定义一个say方法,创建1号dao实现类,重写say方法,输出“我是1号实现类”
2.创建service接口,接口定义一个getuser方法。
创建service实现类,类中创建成员变量,并重写getuser方法

private UserDao user = new UserDaoImpl1();
 @Override
    public void getUser() {
        user.say();
    }

3.在controller层调用service的方法

   public static void main(String[] args) {
        UserService service = new UserServiceImpl();
        service.getUser();
    }

执行输出:
输出结果
【对多态的理解:
做个比喻
接口:腾讯公司
接口中的方法:腾讯要求职员必须为211以上学历
实现类:即腾讯的下属公司,比如光子工作室
实例对象:即具体的员工
实现类必须实现接口中的方法:腾讯的各个部门招聘也必须要求211学历
UserService service = new UserServiceImpl();
可以看成:
腾讯 员工A = new 技术部();
员工A必须具有211以上学历(实现接口方法)
光子工作室可以再添加招聘条件,比如三年工作经验(实现类可以自己定义方法)
员工A既可以说是腾讯员工,也可以说是光子工作室员工。
由于多态的存在,腾讯可以创建更多的下属公司,最终组成庞大的商业帝国。

此时有个问题,假如因为项目需要,Dao接口需要创建多个实现类并调用,该如何实现?
1.创建Dao实现类UserDaoImpl2,重写方法“我是2号实现类”
2.Service层实现类改为

public class UserServiceImpl implements UserService {
    private UserDao user = new UserDaoImpl2();
    @Override
    public void getUser() {
        user.say();
    }
}

3.MyTest中调用并实现
输出结果

如果Dao有多个实现类呢?
在这里插入图片描述
每次需求不同,service层都需要更改代码。这在实际开发中是很浪费时间的。

二、如何改进?增加set方法

之前在service实现类中,我们把对象创建的代码给写死了

private UserDao user = new UserDaoImpl2();

改进一下:

private UserDao user ;

    public void setUser(UserDao user) {
        this.user = user;
    }

controller调用:

        UserServiceImpl service = new UserServiceImpl();
        service.setUser(new UserDaoImpl3());
        service.UserSay();

【有个小知识点:这里如果写成
UserService service = new UserServiceImpl();
那么调用service.setUser会报错
原因:创建接口对象,该对象只能调用接口方法,其实现类自定义的方法不能调用,可以调用重写接口的方法

控制台输出:
在这里插入图片描述

注意:这里可以看出,对象创建的控制权在我们(即程序员)手上。现在将控制权给反转,这就是一种控制反转的概念。
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是Ioc容器,其实现方法是依赖注入。

下面通过一个示例来证明:
1.创建Hello类,成员变量String类型的name,增加get/set方法
2.创建beans.xml 作如下配置

<!--使用Sprng来创建对象,在Spring这些都称为Bean
    类型 变量名 = new 类型()
    Hello hello = new Hello();
    
    id=变量名
    class= new的对象
    property相当于给对象中的属性设置一个值
    -->
   <bean id="hello" class="com.zhengquan.pojo.Hello">
       <property name="name" value="Spring"/>
   </bean>

3.测试

        //获取spring的上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //我们的对象现在都在Spring管理了,我们要使用,直接去里面取出来就可以
        Hello name = (Hello)context.getBean("hello");
        name.show();

输出:
在这里插入图片描述
总结:
在XML中,一个bean相当于一个对象,容器相当于
核心是set方法。
另外,value:具体的值,基本数据类型
ref:y=引用Spring容器中创建好的对象,其他bean的id

通过这种方式,下次根据需求写代码时,业务层service的代码不需要更改了,方便了很多。

三、IOC创建对象的方式
1.使用无参构造创建对象,默认!
2.假设使用有参构造创建对象
a.下标赋值
在标签中添加:
b.根据类型赋值(不建议使用)
在标签中添加:
type使用全限定名
c.直接通过参数名设置
在标签中添加:

sping容器,类似于婚介网站,在注册时就被实例化了,什么时候用,什么时候getbean。

别名:
标签
或者 别名为b或c或d或e

一般用于团队开发,可以将多个配置文件,导入一个xml

四、依赖注入(Dependency Injection)
依赖:bean对象的创建依赖于容器
注入:bean对象中的所有属性,由容器来注入
三种方式
6.1 构造器注入
前面说过了()
6.2 set方式注入
<property… >
6.3 拓展方式注入 (c、p命名空间)
首先导入约束

bean的作用域
1.单例:默认,singleton
2.多例(原型):每次从容器中get,都会产生一个新对象
scope=“prototype”
3.其余的request/session/application

五、自动装配
1.bytype和byname
在这里插入图片描述
2.使用注解自动装配
导入一个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"
       xmlns:context="http://www.springframework.org/schema/context"
       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/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">

@Autowired 直接在属性上使用,可以不用写set方法
如果定义了Autowired的required属性为false,说明这个对象可以为null,否则不能为空
@Qulifier(value="")按名字匹配,自动装配

@Resource是java自带的注解 @Resource(name="") 在JDK11中被移除了
先通过名字查找,名字找不到,再通过类型查找

小结:
@Autowired 默认通过bytype方式实现
@Resource 默认通过byname实现,找不到,则bytype
两者都是用来自动装配的,都可以用在属性字段上

@Component


@Component("user")
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>

注入属性:
1.没set方法,在成员变量上@value(“xxx”)
2.有set方法,在set方法上添加@value(“xxx”)
【强转的一个知识点:
User user=(User)context.getBean(“user”)
等价于 User user=context.getBean(“user”,user.class)

@Component三个衍生注解
@Controller:web层
@Service:service层
@Repository:dao层 四个注解功能一样

@Scope("")设置作用域

小结:
xml 适用于任何场合 维护简单方便
注解 不是自己类使用不了,维护复杂

使用Java的方式配置Spring
完全不使用Spring的xml配置,全权交给java来做
JavaConfig是Spring的一个子项目,在Spring4之后,它成为了一个核心功能
@Configuration
示例:
1.创建User类(没有@Component)

public class User {
    private String name;

    public String getName() {
        return name;
    }

    @Value("郑权")
    public void setName(String name) {
        this.name = name;
    }
}

2.编写配置类(这里@Configuration也不用加)

public class MyConfig {

    @Bean
    public User getUser(){
        return new User();
    }
}

3.测试

public class MyTest2 {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
       User getUser = (User)context.getBean("getUser");
        System.out.println(getUser.getName());
    }
}

个人理解:
@Bean就相当于把某个类添加到容器中了,上图中,User是该类,getUser是Id
@Configuration不太懂,留着以后补坑

AOP:(Aspect Oriented Programming)面向切面编程

1.代理模式
分为静态代理和动态代理

理解代理:
租客-房屋中介-房东,此处中介是代理

静态代理:
代码里的体现:
接口:租房这个事情本身
接口实现类
1.房东,只有一个方法,租房
2.代理类,有房东成员变量,有租房方法,还有其他方法,比如收租金
测试类调用
找代理租房:


//客户类,一般客户都会去找代理!
public class Client {
    public static void main(String[] args) {
        //房东要租房
        Host host = new Host();
        //中介帮助房东
        Proxy proxy = new Proxy(host);
        //你去找中介!
        proxy.rent();
    }
}

在这里插入图片描述
优点:不改变原有代码的基础上,对源代码进行增强
缺点:增加了代码量,开发效率低

如何解决?动态代理

动态代理
动态代理又分为两类:

  1. 基于接口–JDK的动态代理(重点)
  2. 基于类的动态代理:cglib
    还有一个java字节码实现:javasist 【了解】

了解两个类:invocationHandler:调用处理程序 Proxy:代理
【反射包,java.lang.reflect】
一个动态代理类可以代理多个类

AOP实现方式
AOP在Spring中的作用:

  1. 提供声明式事务
  2. 允许用户自定义切面

几个名词:

  • 横切关注点(与业务逻辑无关,但是需要关注的部分,比如日志,安全,缓存等)
  • 切面(ASPECT):横切关注点被模块化的特殊对象,是一个类(前置通知、后置通知等方法实现的那个类?)
  • 通知(Advice):切面中的方法,即对代码增强的方法
  • 目标(Target):被通知对象(?)
  • 代理(Proxy):向目标对象应用通知之后创建的对象(?)
  • 切入点(PointCut):切面通知执行的“地点”的定义(被增强的方法)
  • 连接点(JointPoint):与切入点匹配的执行点

通知的5种类型:

  1. 前置通知
  2. 后置通知
  3. 异常抛出通知
  4. 引介通知
  5. 环绕通知(包含前四种)

下面测试几个实现方法:

第一种实现方法:使用原生Spring API接口
1.添加依赖:

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
    <scope>runtime</scope>
</dependency>

2.创建service层需要增强的方法
在这里插入图片描述
3.写增强方法
在这里插入图片描述
在这里插入图片描述
4.配置文件(注意execution的用法)
在这里插入图片描述

<?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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--注册bean-->
    <bean id="userService" class="com.zhengquan.service.Impl.UserServiceImpl"/>
    <bean id="log" class="com.zhengquan.log.Log"/>
    <bean id="afterlog" class="com.zhengquan.log.AfterLog"/>


    <!--配置aop-->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* com.zhengquan.service.Impl.UserServiceImpl.*(..))"/>
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

5.测试

    @Test
    public void test1(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");

        UserService userService = (UserService)context.getBean("userService");

        userService.insert();
    }

6.结果
在这里插入图片描述
第二种实现方式:自定义类来实现AOP
1.定义切面

public class Diypointcut {

    public void before(){
        System.out.println("===========前=========");
    }

    public void after(){
        System.out.println("===========后=========");
    }
}

2.更改配置文件

    <aop:config>
        <!--自定义切面,ref要引用的类-->
        <aop:aspect ref="diypointcut">
            <!--切入点-->
            <aop:pointcut id="point" expression="execution(* com.zhengquan.service.Impl.UserServiceImpl.*(..))"/>
            <!--通知-->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

3.测试类不变,执行
在这里插入图片描述
第三种实现方式:注解
1.导入依赖

    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>1.8.9</version>
    </dependency>

2.编写切面类

@Aspect
public class AnnoPointCut {

    @Before("execution(* com.zhengquan.service.Impl.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("===========前=========");
    }

    @After("execution(* com.zhengquan.service.Impl.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("===========后=========");
    }

    @Around("execution(* com.zhengquan.service.Impl.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("环绕前");
        //执行方法
        Object proceed = joinPoint.proceed();
        System.out.println("环绕后");

        //获得签名
        Signature signature = joinPoint.getSignature();
        System.out.println("signature"+signature);
        System.out.println(proceed);
    }

}

3.配置文件

    <!--方式三-->
    <bean id="annoPointCut" class="com.zhengquan.diy.AnnoPointCut"/>
    <!--开启注解支持          JDK(默认proxy-target-class="true")   cglib(proxy-target-class="false")   -->
    <aop:aspectj-autoproxy proxy-target-class="true"/>

4.测试类不变,输出
在这里插入图片描述

(注意环绕通知和前置、后置通知的执行顺序)

整合Mybatis
【快速选中一行:定位到行尾,shift+home或者定位到行首,shift+↓】
【lombok依赖中的@Data注解,能自动生成get/set/tostring等方法】
【如果配置文件没放在resources文件夹下,要在pom文件下编写标签在这里插入图片描述

什么是Mybatis-Spring
允许Mybatis参与到Spring的事务管理之中
相关配置说明
(以前数据源配置死的,sqlsessionfactory是用代码写的)
配置Mybatis:
方法一:
1.引入依赖

   <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.0.RELEASE</version>
    </dependency>


    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.4</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>1.8.9</version>
    </dependency>

    <!--Spring操作数据库的话,需要一个spring-jdbc-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.1.9.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.5</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.6</version>
    </dependency>



    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.6</version>
    </dependency>

  </dependencies>

2.resources下创建spring-dao.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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--DataSource:使用spring的数据源替换Mybatis的配置 c3p0 dbcp druid
    这里我们使用Spring提供的JDBC-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&amp;characterEncoding=utf8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--绑定Mybatis配置文件,绑定完之后两个文件就连起来了-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/zhengquan/mapper/*.xml"/>
    </bean>

    <!--SqlSessionTemplate:就是我们使用的sqlsession,在spring整合中换个名-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入sqlSessionfactory 因为它没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <bean id="userMapper" class="com.zhengquan.mapper.UserMapperImpl">
        <property name="sqlSessionTemplate" ref="sqlSession"/>
    </bean>


</beans>

3.sqlSessionTemplate
4.需要给接口加实现类【】
5.将自己写的实现类,注入到spring中
6.测试

注意:
applicationcontext.xml中这样写
在这里插入图片描述
spring-dao.xml就相当于固定死了,以后的操作在applicationcontext中进行

声明式事务

一个使用 MyBatis-Spring 的其中一个主要原因是它允许 MyBatis 参与到 Spring 的事务管理中。而不是给 MyBatis 创建一个新的专用事务管理器,MyBatis-Spring 借助了 Spring 中的 DataSourceTransactionManager 来实现事务管理。
(spring中的事务管理分为声明式事务和编程式事务)

  • 声明式事务:AOP
  • 编程式事务:需要在代码中进行事务的管理(try catch之类,基本不用)

在这里插入图片描述

课堂笔记
完毕

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值