Spring学习笔记(自己用,不全)

1、Spring

1.1 简介

以interface21框架为基础,于2004年3月24日发布1.0版本

Rod Johnson 开发者

spring理念:试现有的技术更加容易使用,本身是一个大杂烩,整合了现有的技术框架

SSM: SpringMvc+Spring+Mybatis

官方下载地址 http://repo.spring.io/release/org/springframework/spring

spring maven

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

1.2 优点

  • spring 是一个开源的免费的框架(容器)
  • 是一个轻量级,非入侵式的框架
  • 控制反转,面向切面编程
  • 支持事务的处里,对框架整合的支持

总结:轻量级的控制反转和面向切面编程的框架

1.3 组成

1.4 扩展

现代化的开发

构建 协调 连接

  • springBoot
    • 一个快速开发的脚手架
    • 基于springboot可以快速的开发单个微服务
    • 约定大于配置
  • springClound
    • 基于springBoot实现的

因为现在大多数公司都在使用springboot进行快速开发,学习springboot的前提,需要完全掌握spring和spring MVC

弊端:违背了原来的理念,配置十分繁琐,人称配置地狱

2、IOC理论推导

1.传统开发

UserDao接口 - UserDaoImpl实现类 UserService业务接口 UserServiceImpl实现类

在之前的业务中,用户的需求会影响我们的代码,我们需要根据用户的需求去修改源代码。太麻烦!!!

用一个Set接口实现 进行动态实现值得注入

  • 之前,程序是主动创建对象,控制权在程序员手上
  • 使用set注入后,程序不在具有主动性,而是编程了被动得接收对象

这种思想,从本质上解决了问题,程序员不用再去管理对象得创建,系统的耦合性降低了,可以更加专注的在业务的实现上,这是IOC的原型

控制反转IOC,是一种设计思想,DI(依赖注入)是实现IOC的一种方法

控制反转是一种通过描述(xml或注解) 并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IOC容器,实现 方法是依赖注入(DI)

3、HelloSpring

1.导入依赖

2.Hello类

package com.liu.pojo;

public class Hello {
    private String str;

    @Override
    public String toString() {
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }
}

3.beans.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="hello" class="com.liu.pojo.Hello">
        <property name="str" value="Spring"/>
    </bean>
</beans>

4.测试

import com.liu.pojo.Hello;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    @Test
    public void HelloSpring(){
        //获取Spring的上下文
        ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
        Hello hello = (Hello)context.getBean("hello");
        System.out.println(hello.toString());
    }
}

ref:引用spring容器创建好的对象

value:具体的值,基本数据类型

4、IOC创建对象的方式

1.使用无参构造创建对象,默认!

2.假设用有参构造创建对象

  • 下标赋值

    <bean id="user" class="com.liu.pojo.User">
        <constructor-arg index="0" value="有参构造"/>
    </bean>
    
  • 不建议使用:通过类型创建

    <bean id="user" class="com.liu.pojo.User">
        <constructor-arg type="java.lang.String" value="有参构造"/>
    </bean>
    
  • 直接通过参数名

    <bean id="user" class="com.liu.pojo.User">
        <constructor-arg name="name" value="有参构造"/>
    </bean>
    

总结:在配置文件加载的时候,容器中管理的对象就已经初始化了

5、spring配置说明

5.1 配置

别名 如果添加了别名,就可以用别名获取到这个对象
<alias name="user" alias="userNew"/>

5.2 Bean的配置

id:bean 的唯一标识符 相当于对象名
class: bean对象对应的全限定名 : 包名+类型
name: 别名 可以取多个,用空格或,隔开
<bean id="user" class="com.liu.pojo.User" name="user1,user3 user4"></bean>

5.3 import

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

假设,现在项目中有多个人开发

三个人负责不同的类开发,不同的类需要注册在不同的bean中。用import将三个合成一个总的

<import resource="beanx.xml"/>
<import resource="beanx2.xml"/>
<import resource="beanx3.xml"/>

6、依赖注入

6.1 构造器注入

看4

6.2 set方式注入【重点】

  • 依赖注入:set注入
    • 依赖:bean对象的创建依赖于容器
    • 注入:bean对象中的所有属性,又容器来注入

【环境搭建】

spring-04-di

pojo:

package com.liu.pojo;

public class Address {
    private String address;

    @Override
    public String toString() {
        return "Address{" +
                "address='" + address + '\'' +
                '}';
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}
public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobby;
    private Map<String,String> card;
    private Set<String> games;
    //get
    
    //set
    //toString   
}

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

    <bean id="address" class="com.liu.pojo.Address">
        <property name="address" value="bean注入 ref"/>
    </bean>
    <bean id="student" class="com.liu.pojo.Student">
        <property name="name" value="普通值注入 value"/>

        <property name="address" ref="address"/>

        <property name="books">
            <array>
                <value>数组注入</value>
                <value>三国</value>
                <value>水浒</value>
                <value>西游</value>
            </array>
        </property>

        <property name="hobby">
            <list>
                <value>list注入</value>
                <value>听歌</value>
                <value>看美女</value>
            </list>
        </property>

        <property name="card">
            <map>
                <entry key="Map注入" value="entry"/>
                <entry key="" value=""/>
                <entry key="身份证" value="1234567890"/>
            </map>
        </property>

        <property name="games">
            <set>
                <value>Set注入</value>
                <value>cf</value>
                <value>lol</value>
            </set>
        </property>

        <property name="info">
            <props>
                <prop key="props注入">prop</prop>
                <prop key="url">www.baidu.com</prop>
                <prop key="root">admin</prop>
            </props>
        </property>
    </bean>
</beans>
设置为空
<property name="">
    <null/>
</property>

测试类

@Test
public void SetTest(){
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    Student student =(Student) context.getBean("student");
    System.out.println(student.toString());
    /*
        * Student
        *   {name='普通值注入 value',
        *   address=Address{address='bean注入 ref'},
        *    books=[数组注入, 三国, 水浒, 西游],
        *   hobby=[list注入, 听歌, 看美女],
        *   card={Map注入=entry, 键=值, 身份证=1234567890},
        *   games=[Set注入, cf, lol], info={root=admin, url=www.baidu.com, props注入=prop}}
        *
         *
        * */
}

6.3 扩展方式注入

P命名空间

需要实体类有无参构造

导入头文件约束

xmlns:p="http://www.springframework.org/schema/p"

使用

<bean id="user" class="com.liu.pojo.User" p:name="张三" p:age="18"/>

C命名空间

需要实体类有有参构造

导入头文件依赖

xmlns:c="http://www.springframework.org/schema/c"

使用

<bean id="user" class="com.liu.pojo.User" c:name="张三" c:age="18"/>

注意点:P命名和C命名空间不能直接使用,需要导入头文件依赖

6.4 bean的作用域

1.单例模式 默认

可以显示设置 在bean 标签 scope=“singleton”

2.原型模式

在bean 标签 scope=“prototype”

每次从容器中get的时候,都会产生一个新对象

3.其他的

request,session,application这些只能在web开发中使用到

7、bean的自动装配

  • 自动装配是Spring满足bean依赖的一种方式
  • Spring会在上下文自动寻找,并自动给bean装配属性

在Spring中有三种装配方式

1.在xml中显示的配置

2.在Java中显示配置

3.隐式的自动装配【重要】

7.1 测试

spring-05

实体类 peopele cat dog

环境搭建 一个人有两个宠物

7.2 ByName自动装配

byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的bean id

<bean id="xxx" class="xxx.xxx.xxx" autowire="byName"></bean>

7.3 ByType自动装配

会自动在容器上下文中查找,和自己对象属性类型相同的bean

<bean id="xxx" class="xxx.xxx.xxx" autowire="byType"></bean>

小结

  • byname的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性和set方法的值一致
  • bytype 的时候,保证所有bean的class唯一,。。属性的类型一致

7.4 使用注解实现自动装配

要使用注解

1.导入约束

2.配置注解的支持

xmlns:context="http://www.springframework.org/schema/context"

<context:annotation-config/>

3.使用

@Autowired

直接在属性上使用就可,也可以在set方式上使用

可以省略set方法了,前提是自动装配的属性在ioc容器中存在

   <context:annotation-config></context:annotation-config>
    <context:component-scan base-package="com.liu"/> 自动扫描包

科普

@Nullable 字段标记了这个注解,说明这个字段可以为null
@Autowired(required=false)  说明这个对象可以为null

@Autowired
@Qualifier(value="xxx")
手动指定唯一的装配值
@Resource 

小结:

@Resource 和@Autowired的区别

  • 都是用于自动装配的,都可以放在属性字段
  • 默认byname,找不到名字,通过byType实现

8、使用注解开发

在Spring4之后,要使用注解开发,必须要保证aop的包导入了

使用需要导入约束

1.bean

@Component:组件,放在类上,说明这个类被spring管理了

@Component
相当于<bean id="user" class="com.liu.pojo.User"></bean>

2.属性注入

@Value(“值”) 放在属性或者set方法上

@Value("张三")
    private String name;

3.衍生的注解

@Component 有衍生注解 功能是一样的

  • dao 【@Repository】
  • service【@Service】
  • controller 【@Controller】

功能是一样的都是代表将某个类注册到spring 中装配bean

需要在bean.xml中 扫描

<context:component-scan base-package="com.liu"/>

4.自动装配

5.作用域

@Scope("")

6.小结

xml和注解

  • xml更加万能,适用于一切场合,维护方便
  • 注解 不是自己类使用不了,维护相对复杂

最佳实现

  • xml用来管理bean
  • 注解只负责完成属性的注入
  • 使用的过程中,只需要注意一个问题,开启注解支持

9、使用Java的方式配置spring

不适应spring的xml配置,全权交给java来做

JavaConfig是spring的一个子项目

spring-07

package com.liu.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class User {
    private String name;

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }

    public String getName() {
        return name;
    }
    @Value("李四")
    public void setName(String name) {
        this.name = name;
    }
}
package com.liu.config;

import com.liu.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Config {

    @Bean
    public User getUser(){
        return new User();
    }
}
import com.liu.config.Config;
import com.liu.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    @Test
    public void testA(){
       ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
       User getUser=context.getBean("getUser",User.class);
        System.out.println(getUser.getName());
    }
}

10、代理模式

为什么要学习代理模式?

springAOP的底层【springAOP 和 springMVC】

代理模式的分类

  • 静态代理
  • 动态代理

10.1 静态代理

角色分析

  • 抽象角色:一般会使用接口或者抽象类来解决
  • 真实角色:被代理的角色
  • 代理角色:代理真实角色,代理真实角色后,一般会做一些附属操作
  • 客户:访问代理角色的人

代码

1接口

2真实角色

3代理角色

4.客户端访问代理角色

代理模式的好处

  • 可以使真实角色的操作更加纯粹,不用去关注一些公共业务
  • 公共业务交给代理角色,实现业务的分工
  • 公共业务发生扩展时,方便集中管理

缺点:

  • 一个真实角色就会产生一个代理角色,代码量翻倍,开发效率变低

10.2 加深理解

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-52fObUn1-1618298149591)(捕获.JPG)]

10.3 动态代理

  • 动态代理和静态代理角色一样
  • 动态代理的代理类是动态生成的,不是我们写好的
  • 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
    • 基于接口–JDK动态代理
    • 基于类:cglib
    • java字节码实现:javasist

需要了解两个类 Proxy 代理 InvocationHandler调用处理程序

动态代理的好处:

一个动态代理类代理的是一个接口,一般对应一类事务

package com.liu;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class Proxy implements InvocationHandler {
    //被代理的接口
    private Rent rent;
    public void setRent(Rent rent) {
        this.rent = rent;
    }

    //生成得到代理类
    public Object getProxy(){
        return java.lang.reflect.Proxy.newProxyInstance(this.getClass().getClassLoader(),
                rent.getClass().getInterfaces(),this);
    }
    //处理代理实例并返回结果
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //动态代理的本质,就是使用反射机制实现
        Object result = method.invoke(rent,args);
        return result;
    }
}
package com.liu;

public class Client {
    public static void main(String[] args) {
        //真实角色
        Host host = new Host();
        //代理角色:现在没有
        Proxy p = new Proxy();
        //通过调用程序处理角色来处理我们要调用的接口对象
        p.setRent(host);
        Rent pro = (Rent)p.getProxy();
        pro.rent();
    }
}

11、AOP

11.1 什么是AOP

面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发的中的一个热点,也是spring框架中的一个重要内容,是函数式编程的一种衍生泛型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高开发的效率

11.2 Aop在Spring中的作用

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

  • 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等
  • 切面(ASPECT) 横切关注点 被模块化的特殊对象。即,它是一个类
  • 通知(Advice) 切面必须完成的工作,即,它是类中的一个方法
  • 目标(Target) 被通知对象
  • 代理 (Proxy) 向目标对象应用通知之后创建的对象
  • 切入点(PointCut) 切面通知 执行的地点的定义
  • 连接点 (jointPoint) 与切入点匹配的执行点

11.3 使用Spring实现Aop

【重点】使用AOP织入,需要导入一个依赖包

<dependencies>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjmatcher</artifactId>
        <version>1.9.6</version>
    </dependency>
</dependencies>

方式一:使用Spring的api接口

package com.liu.log;
import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class AfterLog implements AfterReturningAdvice {
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了"+method.getName()+"方法,返回结果为:"+returnValue);
    }
}
public class Log implements MethodBeforeAdvice {

//method : 要执行的目标对象的方法
//args 参数
//target 目标对象
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+
method.getName()+"被执行了");
}
}
<bean id="userService" class="com.liu.service.UserServiceImpl"/>
<bean id="log" class="com.liu.log.Log"/>
<bean id="afterLog" class="com.liu.log.AfterLog"/>

<aop:config>
    <aop:pointcut id="pointcut" expression="execution(* com.liu.service.UserServiceImpl.*(..))"/>
    <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
    <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>

方式二:自定义类

package com.liu.diy;

public class DiyPointCut {
    public void before(){
        System.out.println("执行前-----");
    }
    public void after(){
        System.out.println("执行后-------");
    }
}
<bean id="diy" class="com.liu.diy.DiyPointCut"/>
<aop:config>
<aop:aspect ref="diy">
<aop:pointcut id="point" expression="execution(* com.liu.service.UserServiceImpl.*(..))"/>

<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>

方式三:注解实现

<bean id="AnnotationPointCut" class=""/>
<aop:aspectj-autoproxy/>
@Aspect //标记这个类是一个切面
public class AnnotationPointCut{
    @Before("execution(* com.liu.service.UserServiceImpl.*(..))")
    public void before(){
        xxx;
    }
}

12、整合MyBatis

步骤:

1.导入相关jar包

junit

mybatis

mysql

spring

aop织入

mybatis-spring

2.编写配置文件

3.测试

12.1 回忆mybatis

1.编写实体类

2.编写核心配置

4.编写接口

5.编写mapper.xml

12.2 mybatis-spring

1.编写数据源配置

2.sqlSessionFactory

3sqlSessionTemplate

4需要给接口加实现类

依赖

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.46</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.2.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjmatcher</artifactId>
        <version>1.9.6</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.2</version>
    </dependency>
</dependencies>
<build>
    <resources>
        <resource>
            <directory>src/main/resource</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

实体类 set/get/tostring/有参/无参

public class User {
    private int id;
    private String name;
    private String pwd;
}

mybatis核心配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <package name="com.liu.pojo" />
    </typeAliases>
</configuration>

mybatis接口实现

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.liu.mapper.UserMapper">

    <select id="getUser" resultType="user">
        select * from mybatis.user;
    </select>
</mapper>

userMapperImpl

package com.liu.mapper;

import com.liu.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

public class UserMapperImpl implements UserMapper{
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    public List<User> getUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.getUser();
    }
}

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: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
        https://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:com/liu/mapper/*.xml"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <bean id="userMapper" class="com.liu.mapper.UserMapperImpl">
        <property name="sqlSession" value="sqlSession"/>
    </bean>
</beans>

13、声明式事务

1.事务

  • 要么都成功,要么都失败
  • 确保完整性和一致性

事务的ACID原则

  • 原子性
  • 一致性
  • 隔离性- 多个业务操作同一个资源
  • 持久性-事务一旦提交,结果不在影响

2.spring中的事务管理

  • 声明式事务 AOP
  • 编程式事务 在代码中进行事务的管理
配置声明式事务
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DateSourceTransactionManager">
	<property name="dataSource" ref="dataSource"/>
   
</bean>

结合AOP实现事务的织入
<tx:advice id="txAdvice" transaction-maager="transactionManager">
	<tx:attributer>
    	<tx:method name="*" propagation="REQUIRED"/>
    </tx:attributer>
</tx:advice>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值