Spring基础

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.20.RELEASE</version>
    </dependency>  
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.24</version>
    </dependency>
</dependencies>

一、简介

1、Spring简介

官网:Spring Framework

2. 优点

1.2 优点
Spring是一个开源的免费的框架(容器)!
Spring是一个轻量级的、非入侵式的框架!
控制反转(IOC),面向切面编程(AOP)!
支持事务的处理,对框架整合的支持!
总之:Spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架!
1.3 组成

3. 组成

4. 拓展

 使用一个set接口实现,已经发生了革命性的变化。举例:

public interface UserDao {
    void getUser();
}
public class UserDaoImpl implements UserDao{
    @Override
    public void getUser() {
        System.out.println("获得用户信息");
    }
}
public class UserDaoMysqlImpl implements UserDao{
    @Override
    public void getUser() {
        System.out.println("获得mysql用户信息");
    }
}
public interface UserService {
    void getUser();
}
public class UserServiceImpl implements UserService{
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void getUser() {
        userDao.getUser();
    }
}

测试:

@Test
public void test2(){
	UserServiceImpl userService = new UserServiceImpl();
	userService.setUserDao(new UserDaoImpl());
	userService.getUser();
	userService.setUserDao(new UserDaoMysqlImpl());
	userService.getUser();
}

 运行结果:

之前程序时主动创建对象,控制权在程序员手上;使用了set注入后,程序不再具有主动性,而是变成了被动的接收对象!从本质上解决了问题,程序员不用再去管理对象的创建,系统的耦合性大大降低,可以更加专注在业务实现上。这是IOC的原型。

二、IOC本质

三、举例入门

spring文档:Core Technologies (spring.io)

package com.wlp.pojo;

public class Hello {
    private String str;


    public String getStr() {
        return str;
    }

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

    @Override
    public String toString() {
        return "hello: "+ str;
    }
}

文档1.2.1中复制以下配置语句,命名为bean.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

<!--    使用Spring来创建对象,在Spring这些都成为Bean
        类型 变量名 = new 类型();
        Hello hello = new Hello();
        
        id = 变量名
        class = new 的对象;
        property 相当于给对象中的属性设置一个值!
        property中的 name 为变量名,value为具体属性值,ref 引用容器中创建好的对象
        这个过程就叫做控制反转
-->
    <bean id="hello" class="com.wlp.pojo.Hello">
        <property name="str" value="Spring"/>  Hello类中有个叫str的属性
    </bean>
</beans>

测试类:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //Spring容器:获取Spring的上下文对象!
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //目前,对象都在Spring中管理了,如果要使用,直接去里面取出来就可以。
        Object hello = context.getBean("hello");  // 参数为bean的id
        System.out.println(hello.toString());
    }
}

前两个为dao包中的类,第三个为service包中的类:

<bean id="userDaoImpl" class="com.wlp.dao.UserDaoImpl"/>
<bean id="mysqlImpl" class="com.wlp.dao.UserDaoMysqlImpl"/>
<bean id="UserServiceImpl" class="com.wlp.service.UserServiceImpl">
    <!--
    ref: 引用Spring容器中创建好的对象
    value:具体的值,基本数据类型!
    -->
    <property name="userDao" ref="mysqlImpl"/>
</bean>

依赖注入:利用set进行注入,所以实体类中必须有set方法。

四、IOC创建对象的方式

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

无参构造器或者默认构造器时可以使用property的方法

<bean id="UserServiceImpl" class="com.wlp.service.UserServiceImpl">
    <property name="userDao" ref="mysqlServiceImpl"/>
</bean>

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

(1)下标赋值

<bean id="user" class="com.wlp.pojo.User">
    <constructor-arg index="0" value="wlp"/>
</bean>

(2)通过类型创建(基本类型直接写,引用类型写全名)不建议使用

<bean id="user" class="com.wlp.pojo.User">
    <constructor-arg type="java.lang.String" value="WQCR"/>
</bean>

(3)直接通过参数名

<bean id="user" class="com.wlp.pojo.User">
    <constructor-arg name="name" value="wlp"/>
</bean>

总结:在配置文件加载的时候,容器中管理的对象就已经初始化了,即xml中所有的bean对象都被注册了,而不管用不用。

五、Spring配置

1. 别名

使用alias或者在bean中加标签属性“name”, name属性可以有多个属性值,多个属性值之间可以用逗号,分号,空格分开

<bean id="user" class="com.wlp.pojo.User" name=" ">
    <constructor-arg name="name" value="wlp"/>
</bean>
<alias name="user" alias="myUser"/>

2. Bean的配置

id:bean的唯一标识符,也就是相当于对象名;

class:bean 对象所对应的全限定名:包名+类型;

name:也是别名,而且name可以同时取多个别名;

3. import

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

假设,现在项目中有多个人开发,这三个人负责不同的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的!

  • 张三
  • 李四
  • 王五

创建applicationContext.xml配置文件,用来统一管理不同开发人员创建的bean.xml文件:

<import resource="beans.xml">
<import resource="beans2.xml">
<import resource="beans3.xml">

使用的时候,直接使用总的配置就可以,也就是:

//Spring容器:获取Spring的上下文对象!
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

六、DI依赖注入

1. 构造器注入

前面说过

2. set方式注入【重点】

依赖注入:Set注入!

        依赖:bean对象的创建依赖于容器!

        注入:bean对象中的所有属性,由容器来注入!

(1)环境搭建

复杂类型

//Address类
package com.wlp.pojo;

public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
    
    @Override
    public String toString() {
        return "address : " + address;
    }
}


//Student类
package com.wlp.pojo;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbies;
    private Map<String, String> card;
    private Set<String> games;
    private String wife;
    private Properties info;
    
    @Override
    public String toString() {
        return name + " \n" + address + " \n" + Arrays.toString(books) + " \n" + hobbies + " \n" + card + " \n" + games +
                " \n" + wife + " \n" + info;
    }
}

(2)set注入配置

<bean name="address" class="com.wlp.pojo.Address">
    <property name="address" value="上海长宁"/>
</bean>
<bean id="student" class="com.wlp.pojo.Student">
    <property name="name" value="wlp"/> 普通注入
    <property name="address" ref="address"/>  bean注入
    <property name="books">
        <array>
            <value>三国</value>
            <value>西游</value>
            <value>水壶</value>
            <value>红楼</value>
        </array>
    </property>
    <property name="card">
        <map>
            <entry key="身份证:" value="130000199010200990"></entry>
            <entry key="工行卡:" value="62834950000199010200990"></entry>
        </map>
    </property>
    <property name="games">
        <set>
            <value>消消乐</value>
            <value>跳一跳</value>
        </set>
    </property>
    <property name="hobbies">
        <list>
            <value>唱歌</value>
            <value>跳舞</value>
            <value>滑冰</value>
        </list>
    </property>
    <property name="info">
        <props>
            <prop key="url">jdbc:mysql:3306</prop>
            <prop key="name">root</prop>
            <prop key="password">mysql</prop>
        </props>
    </property>
    <property name="wife">
        <null/>
    </property>
</bean>

(3)测试真实对象

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student);
    }
}

3. 拓展方式注入

p标签和c标签:

<?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:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--    name + " " + address + " " + books + " " + hobbies + " " + card + " " + games + " " + wife + " " + info-->
<!--    p命名空间注入,可以直接注入属性的值:property-->
    <bean id ="user" class="com.wlp.pojo.User" p:name="wlp" p:age="27"/>
<!--    c命名空间注入,可以通过构造器注入,constructor-args  -->
    <bean id="user" class="com.wlp.pojo.User" c:age="25" c:name="WQCR"/>
</beans>

测试:

ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
User user = context.getBean("user", User.class);  //getBean中用了反射可以直接返回相应类,不再需要强转
System.out.println(user.toString());ring());

注意点:

p命名和c命名空间不能直接使用,需要导入xml约束! (且不能同时)

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

p对应的set方式注入;c对应的构造器注入。c命名时,在实体类中必须有有参构造器。

4. bean的作用域

(1)单例模式(Spring默认机制,多用于单线程,同一个bean,每次获取的都是同一个对象)(面试)

id="accountService" class="com.something.DefaultAccountService" scope="singleton"/>

(2)原型模式:每次从容器中get的时候,都会产生一个新对象!多用于多线程

id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>

(3)其余的request、session、application,这些个只能在web开发中使用到

七、Bean的自动装配

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

在Spring中有三种装配的方式:

(1)在xml中显示地配置

(2)在java中显示地配置

(3)隐式地自动装配bean【重要】

1. ByName自动装配

<bean id="dog" class="com.wlp.pojo.Dog"/>
<bean id="cat" class="com.wlp.pojo.Cat"/>
<!--    byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的bean id-->
<bean id="people" class="com.wlp.pojo.People" autowire="byName">
	<property name="name" value="wlp~"/>
</bean>

2. ByType自动装配

<bean class="com.wlp.pojo.Dog"/>
<bean class="com.wlp.pojo.Cat"/>
<!--    byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean-->
<bean id="people" class="com.wlp.pojo.People" autowire="byType">
	<property name="name" value="wlp~"/>
</bean>

小结:

  • byName的时候,需要保证所有的bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!

  • byType的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致!

3. 使用注解实现自动装配

jdk1.5支持的注解,Spring2.5就支持注解了!

使用注解须知:

  1. 导入约束。context的约束

  2. 开启注解的支持:<context:annotation-config/>

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
    <!--开启注解的支持-->
    <context:annotation-config/>
    <bean id="dog" class="com.wlp.pojo.Dog"/>
    <bean id="cat" class="com.wlp.pojo.Cat"/>
    <bean id="people" class="com.wlp.pojo.People">
        <property name="name" value="wlp~"/>
    </bean>
</beans>

实体类中注解为@Autowired

public class People {
//    如果显示定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
    @Autowired(required = false)
    private Dog dog;
    @Autowired
    private Cat cat;
    private String name;
}

@Autowired

  • 直接在属性上使用即可!也可以在set方式上使用!
  • 使用Autowired就可以不用编写set方法了,前提是这个自动装配的属性在IOC(Spring)容器中存在,且符合名字byName!
  • 如果显示定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空。

@Nullable 说明这个字段可以为null

如果@Autowired 自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,可以使用@Qualifier(value="xxx")去配合@Autowired的使用,指定一个唯一的bean对象注入!

<bean id="dog222" class="com.wlp.pojo.Dog"/>
<bean id="cat3" class="com.wlp.pojo.Cat"/>
<bean id="people" class="com.wlp.pojo.People">
    <property name="name" value="wlp~"/>
</bean>

@Resource:

两种情况:① 保证有一个bean的id为实体类的名字;② 保证class的属性值指向的实体类唯一。

小结:

@Resource 和 @Autowired 的区别:

  • 都是用来自动装配的,都可以放在属性字段上;

  • @Autowired 通过byType的方式实现,而且必须要求这个对象存在!【常用】

  • @Resource默认通过byName 的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下,则报错!【常用】

  • 执行顺序不同:@Autowired 通过byType的方式实现;@Resource默认通过byName 的方式实现

八、使用注解开发

1. bean

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

使用注解需要导入context约束,增加注解的支持!

<context:annotation-config/>   此约束适用于所有的注解,不管注解属不属于spring

<context:component-scan base-package="com.wlp.pojo">  只适用于该包下的spring注解

2. 属性如何注入

@Component
public class User {
    public String name;

    //    相当于 <property name="name" value="wlp"/>
    @Value("wlp")
    public void setName(String name) {
        this.name = name;
    }
}

3. 衍生的注解

@Component有几个衍生注解,在web开发中,会按照MVC三层架构分层!

  1.         dao/mapper 【@Repository】
  1.         service 【@Service】
  1.         controller【@Controller】

这四个注解功能都一样,都是代表将某个类注册到Spring中,装配Bean。

4. 自动装配注解

注解说明:

@Autowired:自动装配通过 类型 -> 名字,如果@Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value="xxx");

@Nullable:当字段标记了这个注解,说明该字段可以为null;

@Resource:自动装配,通过 名字 -> 类型

5. 作用域

@Component
@Scope("singleton")
public class User {
    public String name;

    //    相当于 <property name="name" value="wlp"/>
    @Value("wlp")
    public void setName(String name) {
        this.name = name;
    }
}

6. 小结

xml 与 注解:

  • xml更加万能,适用于任何场合!维护更加简单方便

  • 注解:不是自己的类就使用不了,维护相对复杂!

  • xml用来管理bean;

  • 注解只负责完成属性的注入;

  • 使用过程中只需要注意一个问题:必须让注解生效,需要开启注解的支持

<context:annotation-config/> 
<!-- 指定要扫描的包,该包下的注解就会生效--> 
<context:component-scan base-package="com.wlp"/>

九、使用JavaConfig实现配置

使用注解配置方式创建容器。

新建实体类,在pojo目录下

//这里这个注解的意思是:该类被Spring接管了,注册到了容器中
@Component
public class User {
    public String name;

    public String getName() {
        return name;
    }

    @Value("wlp")   //属性注入值
    public void setName(String name) {
        this.name = name;
    }

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

配置类:

//这个也是Spring容器托管,注册到容器中,因为他本来就是一个@Component
//@Configuration代表这是一个配置类,等同于之前的beans.xml
@Configuration
@ComponentScan("com.wlp.pojo")    //扫描实体类所在的包
@Import(UserConfig2.class)        //UserConfig2是User的另一个配置类,该类同样需要声明@Configuration, 通过@Import整合到UserConfig类中
public class UserConfig {
//    注册一个bean,就相当于之前写的一个bean标签
//    该方法的名字,就相当于bean标签中的id属性
//    该方法的返回值,就相当于bean标签中的class属性
    @Bean
    public User getUser() {
        return new User();   //就是返回要注入到bean的对象!
    }
}

测试类:

public class MyTest {
    public static void main(String[] args) {
//        如果完全使用了配置类方式去做,就只能通过 AnnotationConfig 上下文来获取容器,通过配置类的class对象加载!
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(UserConfig.class);
        User getUser = context.getBean("getUser", User.class); 
        System.out.println(getUser.name);
    }
}

十、AOP

代理模式是SpringAOP的底层 【面试:SpringAOP 和 SpringMVC】

1. 静态代理

角色分析:

  • 抽象角色:一般会使用接口或者抽象类来解决

  • 真实角色:被代理的角色

  • 代理角色:代理真实角色,代理真实角色后,一般会做一些附属操作

  • 客户:访问代理对象的人!

代码步骤:

(1)接口

public interface User {
    public void add();
    public void delete();
    public void update();
    public void query();
}

(2)真实角色

public class Service implements User {
    public void add() {
        System.out.println("增");
    }

    public void delete() {
        System.out.println("删");

    }

    public void update() {
        System.out.println("改");

    }

    public void query() {
        System.out.println("查");

    }
}

(3)代理角色

public class Proxy implements User{
    public Service serv;

    public Proxy(Service serv) {
        this.serv = serv;
    }

    public Service getServ() {
        return serv;
    }

    public void setServ(Service serv) {
        this.serv = serv;
    }

    public void add() {
        log("add");
        serv.add();
    }

    public void delete() {
        log("delete");
        serv.delete();

    }

    public void update() {
        log("update");
        serv.update();

    }

    public void query() {
        log("query");
        serv.query();

    }

    public void log(String msg){
        System.out.println("调用了" + msg + "方法");
    }
}

(4)客户端访问代理角色

public class Client {
    public static void main(String[] args) {
        Service service = new Service();
        Proxy proxy = new Proxy(service);
        proxy.query();
    }
}

租房的例子:

public interface Rent {
    public void rent();
}
public class Host implements Rent {
    public void rent() {
        System.out.println("房东我要出租房子");
    }
}
public class Proxy implements Rent{
    private Host host;



    public Proxy(Host host) {
        this.host = host;
    }

    public Host getHost() {
        return host;
    }

    public void setHost(Host host) {
        this.host = host;
    }

    public void rent(){
        seeHouse();
        host.rent();
        contract();
        fare();
    }

    public void seeHouse(){
        System.out.println("看房子");
    }

    public void fare(){
        System.out.println("收房租");
    }

    public void contract(){
        System.out.println("签合同");
    }
}
public class Client {
    public static void main(String[] args) {
        Host host = new Host();
        Proxy proxy = new Proxy(host);
        proxy.rent();
    }
}

代理模式的好处:

  • 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务

  • 公共业务就交给代理角色!实现了业务的分工!

  • 公共业务发生扩展的时候,方便集中管理!

缺点:

  • 一个真实角色就会产生一个代理角色;代码量会翻倍--开发效率降低。

2. 动态代理

  • 动态代理和静态代理角色一样

  • 动态代理的代理类是动态生成的,不是直接写好的

  • 动态代理分为两大类:基于接口的动态代理,基于类的动态代理

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

动态代理的好处:

  • 可以使真实角色的操作更加纯粹,不用去关注一些公共的业务

  • 公共业务就交给代理角色,实现了业务的分工!

  • 公共业务发生拓展的时候,方便集中管理

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

  • 一个动态代理类可以代理多个类,只要是实现了同一个接口即可

代理类:

//用该类 自动生成代理类!
public class ProxyInvocationHandler implements InvocationHandler {

//    被代理的接口
    private Rent rent;

    public void setRent(Rent rent) {
        this.rent = rent;
    }
//    生成得到代理类
    public Object getProxy(){
        return Proxy.newProxyInstance(
                this.getClass().getClassLoader(),
                rent.getClass().getInterfaces(), this);
    }

//    处理代理实例,并返回结果
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
//        动态代理的本质,就是使用反射机制实现!
        seeHouse();
        Object result = method.invoke(rent, args);
        fare();
        return result;
    }

    public void seeHouse(){
        System.out.println("看房子");
    }

    public void fare(){
        System.out.println("收中介费");
    }

}

客户类:

public class Client {
    public static void main(String[] args) {
//        真实角色
        Host host = new Host();

//        代理角色
        ProxyInvocationHandler pih = new ProxyInvocationHandler();
//        通过调用程序处理角色来处理要调用的的接口对象!
        pih.setRent(host);
        Rent proxy = (Rent) pih.getProxy();
        proxy.rent();
    }
}

自动生成代理类:

//用该类 自动生成代理类!
public class ProxyInvocationHandler implements InvocationHandler {

//    被代理的接口
    private Object target;

    public void setTarget(Object target) {
        this.target = target;
    }
//    生成得到代理类
    public Object getProxy(){
        return Proxy.newProxyInstance(
                this.getClass().getClassLoader(),
                target.getClass().getInterfaces(), this);
    }

//    处理代理实例,并返回结果
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
//        动态代理的本质,就是使用反射机制实现!
        log(method.getName());
        Object result = method.invoke(target, args);
        return result;
    }

    public void log(String msg){
        System.out.println("执行了" + msg + "方法");
    }
}

测试类:

public class Client {
    public static void main(String[] args) {
        Service service = new Service();
        ProxyInvocationHandler pih = new ProxyInvocationHandler();
        pih.setTarget(service);
        User proxy = (User) pih.getProxy();
        proxy.query();
    }
}

十一、AOP

1. 什么是AOP

2. AOP在Spring中的作用 

aop在不改变原有代码的情况下,去增加新的功能。 

3.  使用Spring接口实现AOP

导入依赖

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.19</version>
</dependency>
public interface UserService {
    public void add();
    public void del();
    public void upd();
    public void sel();
}
public class UserServiceImpl implements UserService{
    public void add() {
        System.out.println("增");
    }
    public void del() {
        System.out.println("删");
    }
    public void upd() {
        System.out.println("改");
    }
    public void sel() {
        System.out.println("查");
    }
}
public class Log implements MethodBeforeAdvice {
    public void before(Method method, Object[] args, Object target) throws Throwable {
//        method:要执行的目标对象的方法
//        args:参数
//        target:目标对象
        System.out.println(target.getClass().getName() + "的" + method.getName()+"被执行了");
    }
}
public class AfterLog implements AfterReturningAdvice {
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了" + method.getName() + "方法,返回结果为:" + returnValue);
    }
}

<?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:c="http://www.springframework.org/schema/c" 
       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/mvc 
        https://www.springframework.org/schema/mvc/spring-mvc.xsd 
        http://www.springframework.org/schema/aop 
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    <bean id="log" class="com.wlp.log.Log"/>
    <bean id="afterLog" class="com.wlp.log.AfterLog"/>
    <bean id="userServiceImpl" class="com.wlp.service.UserServiceImpl"/>
<!--    方式一:使用原生Spring API接口-->
<!--    配置aop:需要导入aop的约束-->
    <aop:config>
<!--        切入点:expression:表达式, execution(要执行的位置!* * * * * *)-->
        <aop:pointcut id="pointcut" expression="execution(* com.wlp.service.UserServiceImpl.*(..))"/>
<!--        执行环绕增强-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>
</beans>
public class NewTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//        动态代理代理的是接口:UserService
        UserService userServiceImpl = (UserService) context.getBean("userServiceImpl");
        userServiceImpl.add();
    }
}

执行结果:

4. 自定义实现AOP【切面定义】

public class Diy {
    public void before(){
        System.out.println("首先输出的");
    }
    public void after(){
        System.out.println("最后输出的");
    }
}
<!--    方式二:自定义类-->
<bean id="diy" class="com.wlp.diy.Diy"/>
<aop:config >
<!--        自定义切面,ref即要引用的类-->
	<aop:aspect ref="diy">
<!--            切入点-->
		<aop:pointcut id="point" expression="execution(* com.wlp.service.UserServiceImpl.*(..))"/>
<!--            通知-->
		<aop:before method="before" pointcut-ref="point"/>
		<aop:after method="after" pointcut-ref="point"/>
	</aop:aspect>
</aop:config>

5. 使用注解方式实现AOP

<!--方式三-->
<bean id="annotationPointcut" class="com.wlp.diy.AnnotationPointcut"/>
<!--开启注解支持-->
<aop:aspectj-autoproxy/>
@Aspect   //标注该类是一个切面
public class AnnotationPointcut {
    @Before("execution(* com.wlp.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("before");
    }
    @After("execution(* com.wlp.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("after");
    }
    //    在环绕增强中,可以给定一个参数,代表要获取处理切入的点
    @Around("execution(* com.wlp.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable{
        System.out.println("环绕前");
        Signature signature = jp.getSignature();   //获得签名
        System.out.println("signature:" + signature);
        Object proceed = jp.proceed();   //执行方法
        System.out.println("环绕后");
    }
}

 运行结果:环绕前  方法执行前  方法执行  环绕后  方法执行后

十二、整合Mybatis

步骤:

(1)导入相关jar包

  • junit
  • mybatis
  • mysql数据库
  • spring相关的
  • aop置入
  • mybatis-spring

(2)编写配置文件

(3)测试

mybatis-spring:

mybatis-spring

<!-- mybatis整合spring -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.1.0</version>
</dependency>

1. Mybatis-spring

  1. 编写数据源配置

  2. sqlSessionFactory

  3. sqlSessionTemplate

  4. 需要给接口加实现类

  5. 将自己写的实现类,注入到Spring中

  6. 测试使用即可

user.java

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

UserMapper接口

public interface UserMapper { 
	public List<User> getUser(); 
}

UserMapper.xml

<?xml version="1.0" encoding="GBK" ?> 
<!DOCTYPE mapper 
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
	"https://mybatis.org/dtd/mybatis-3-mapper.dtd"> 
<!--namespace绑定一个对应的mapper接口--> 
<mapper namespace="com.wlp.mapper.UserMapper"> 
	<select id="getUser" resultType="User"> 
		select * from mybatis.user 
	</select> 
</mapper>

mybatis-config.xml

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

spring-dao.xml:用spring管理数据源、sqlSessionFactory等

<?xml version="1.0" encoding="GBK"?> 
<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:c="http://www.springframework.org/schema/c" 
	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/mvc 
	https://www.springframework.org/schema/mvc/spring-mvc.xsd 
	http://www.springframework.org/schema/aop 
	https://www.springframework.org/schema/aop/spring-aop.xsd"> 
	<!-- DataSource:使用Spring的数据源替代Mybatis的配置--> 
	<!-- 这里是用Spring提供的JDBC:org.springframework.jdbc.datasource--> 
	<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?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/> 
		<property name="username" value="root"/> 
        <property name="password" value="mysq123"/> 
	</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/wlp/mapper/*.xml"/> 
	</bean> <!-- sqlSessionTemplate:就是使用的sqlSession--> 
	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> 
		<!-- 只能用构造器注入sqlSessionFactory, 因为它没有set方法--> 
		<constructor-arg index="0" ref="sqlSessionFactory"/> 
	</bean> 

</beans>

UserMapperImpl.java

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(); 
	} 
}

applicationContext.xml

<?xml version="1.0" encoding="GBK"?> 
<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:c="http://www.springframework.org/schema/c" 
	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/mvc 
		https://www.springframework.org/schema/mvc/spring-mvc.xsd 
		http://www.springframework.org/schema/aop 
		https://www.springframework.org/schema/aop/spring-aop.xsd"> 
    <!--应用spring-dao.xml的配置-->
	<import resource="spring-dao.xml"/> 
	<bean id="userMapper" class="com.wlp.mapper.UserMapperImpl"> 
		<property name="sqlSession" ref="sqlSession"/> 
	</bean> 
</beans>

MyTest

public class MyTest { 
	public static void main(String[] args) { 
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 
		UserMapper userMapper = context.getBean("userMapper", UserMapper.class); 
		List<User> user = userMapper.getUser(); 
		for (User user1 : user) { 
			System.out.println(user1); 
		} 
	} 
}

第二种方式:(不太建议使用)

 新建UserMapperImpl2.java

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper { 
	public List<User> getUser() { 
		UserMapper mapper = getSqlSession().getMapper(UserMapper.class); 
		return mapper.getUser(); 
	} 
}

SqlSessionDaoSupport类要有单参构造器,需要注入一个SqlSessionFactory.

所以需要在以下配置文件中注入 SqlSessionFactory,其中ref来自于spring-dao.xml 中注册的SqlSessionFactory实例。

applicationContext.xml中

<bean id="userMapper2" class="com.wlp.mapper.UserMapperImpl2"> 
	<property name="sqlSessionFactory" ref="sqlSessionFactory"/> 
</bean>

十三、声明式事务

1. 事务

把一组业务当成一个业务来做,要么都成功,要么都失败

事务在项目开发中十分重要,涉及到数据的一致性问题

确保完整性和一致性

事务ACID原则:

  • 原子性

  • 一致性

  • 隔离性:多个业务可能操作同一个资源,防止数据损坏

  • 持久性:事务一旦提交,无论系统发生什么问题,结果都不会被影响,被持久化写到存储器中

2. Spring中的事务管理

声明式事务:AOP

编程式事务:需要在代码中进行事务的管理

为什么需要事务:

如果不配置事务,可能存在数据提交不一致的情况;

如果不在Spring中去配置声明式事务,就需要在代码中手动配置事务

事务在项目开发中十分重要,涉及到数据的一致性和完整性问题

spring-dao.xml中配置

<!--    结合AOP实现事物的置入-->
<!--    配置事务的类;-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--        给哪些方法配置事务-->
<!--        配置事务的传播特性:new propagation(默认就有)-->
        <tx:attributes>
<!--            <tx:method name="add" propagation="REQUIRED"/>-->
<!--            <tx:method name="delete" propagation="REQUIRED"/>-->
<!--            <tx:method name="update" propagation="REQUIRED"/>-->
<!--            <tx:method name="query" read-only="true"/>-->
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
<!--    配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.wlp.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>

案例:

user.java

@Data 
@AllArgsConstructor 
@NoArgsConstructor 
	public class User { 
	private int id; 
	private String name; 
	private String pwd; 
}

UserMapper接口

public interface UserMapper { 
	public List<User> getUser(); 
	public int addUser(User user); 
	public int delUser(int id); 
}

UserMapper.xml

<?xml version="1.0" encoding="GBK" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace绑定一个对应的mapper接口-->
<mapper namespace="com.wlp.mapper.UserMapper">
    <select id="getUser" resultType="User">
        select * from mybatis.user
    </select>
    <insert id="addUser" parameterType="user">
        insert into mybatis.user values(#{id}, #{name}, #{pwd})
    </insert>
    <delete id="delUser">
        deletes from mybatis.user where id = #{id}
    </delete>
</mapper>

mybatis-config.xml

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

spring-dao.xml

需要在文件头中加入:

xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
<?xml version="1.0" encoding="GBK"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:c="http://www.springframework.org/schema/c" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<!--    DataSource:使用Spring的数据源替代Mybatis的配置-->
<!--    这里是用Spring提供的JDBC:org.springframework.jdbc.datasource-->
    <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?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="mysq123"/>
    </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/wlp/mapper/*.xml"/>
    </bean>
<!--    sqlSessionTemplate:就是使用的sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--        只能用构造器注入sqlSessionFactory, 因为它没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
<!--    配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!--    结合AOP实现事物的置入-->
<!--    配置事务的类;-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--        给哪些方法配置事务-->
<!--        配置事务的传播特性:new propagation(默认就有)-->
        <tx:attributes>
<!--            <tx:method name="add" propagation="REQUIRED"/>-->
<!--            <tx:method name="delete" propagation="REQUIRED"/>-->
<!--            <tx:method name="update" propagation="REQUIRED"/>-->
<!--            <tx:method name="query" read-only="true"/>-->
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
<!--    配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.wlp.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
</beans>

applicationContext.xml

<?xml version="1.0" encoding="GBK"?>
<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:c="http://www.springframework.org/schema/c" 
       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/mvc 
        https://www.springframework.org/schema/mvc/spring-mvc.xsd 
        http://www.springframework.org/schema/aop 
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    <import resource="spring-dao.xml"/>
    <bean id="userMapper" class="com.wlp.mapper.UserMapperImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>

UserMapperImpl.java

public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {
	// private SqlSessionTemplate sqlSession; 
	// public void setSqlSession(SqlSessionTemplate sqlSession){ 
		// this.sqlSession = sqlSession; 
	// } 
	public List<User> getUser(){ 
		User user = new User(2, "fgff999f", "hfjahlfa"); 
		UserMapper mapper = getSqlSession().getMapper(UserMapper.class); 
		mapper.addUser(user); mapper.delUser(3); 
		return mapper.getUser(); 
	} 
	public int addUser(User user) { 
		UserMapper mapper = getSqlSession().getMapper(UserMapper.class); 
		return mapper.addUser(user); 
	} 
	public int delUser(int id) { 
		UserMapper mapper = getSqlSession().getMapper(UserMapper.class); 
		return mapper.delUser(id); 
	} 
}

测试类:

public class MyTest { 
	public static void main(String[] args) { 
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 
		UserMapper userMapper = context.getBean("userMapper", UserMapper.class); 
		List<User> user = userMapper.getUser(); 
		for (User user1 : user) { 
			System.out.println(user1); 
		} 
	} 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值