Spring学习笔记

本文介绍了Spring框架的基础概念,包括Spring的历史、下载途径、优点和主要组成部分。重点讲解了Spring的IOC(控制反转)理论及其实现方式,以及如何在Spring配置文件中进行Bean的管理和依赖注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. Spring

1.1 地址

官网:

https://spring.io/projects/spring-framework

官方下载地址:

https://repo.spring.io/ui/native/release/org/springframework/spring

使用手册:

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core

mvnrepository仓库:

https://mvnrepository.com/

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.12</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.12</version>
</dependency>

1.2 优点

  • spring是一个开源的免费的框架(容器)
  • spring是一个轻量级的,非入侵式的框架(导入后原先项目依然可以用)
  • 控制反转(IOC),面向切面编程(AOP)
  • 支持事务的处理,对框架整合的支持

1.3 组成

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cUtB6P1t-1640586044505)(E:\Typroa笔记\Spring.assets\image-20211130123944926.png)]

1.4 扩展

spring -> spring Boot(Build Anything) -> Spring Cloud(coordinate anything) -> Spring Cloud Data Flow(connect Everything)

Spring Boot

  1. 一个快速开发的脚手架
  2. 基于SpringBoot可以快速的开发单个微服务
  3. 约定大于配置

Spring Cloud:

  1. SpringCloud是基于SpringBoot实现的

Spring+SpringMvc=SpringBoot

2. IOC

2.1 IOC理论推导(原型)

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

之前:程序是主动创建对象,控制器在程序员手中!

public class UserServiceImpl implements UserService{
    private UserDao userDao = new UserDaoImpl();  //单独的接口,需要程序员新建
    //private UserDao userDao = new UserSqlImpl();  //第二个需求
    public void getUser() {
        userDao.getUser();
    }
    //测试
@Test
    public void test1(){
        UserService userService = new UserServiceImpl();
        userService.getUser();
    }

**之后:**我们使用一个set接口实现。使用set注入后,程序不在具有主动性,而是变成了被动的接受对象!

public class UserServiceImpl implements UserService{
	private UserDao userDao;
    //利用set进行动态实现值的注入  
    public void setUserDao(UserDao userDao){
        this.userDao=userDao;
    }
    public void getUser() {
     userDao.getUser();
    }
//测试:
@Test
    public void test1(){
        //用户实际调用的是业务层,dao层它们不需要接触
        UserService userService = new UserServiceImpl();
        ((UserServiceImpl) userService).setUserDao(new UserDaoImpl());  //new UserDaoImpl代表需求参数,可改变
        userService.getUser();
    }

2.2 IOC本质

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ObijdyRy-1640586044507)(E:\Typroa笔记\Spring.assets\image-20211130160247062.png)]

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

采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到零配置的目的。

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

控制:谁来控制对象的创建,传统的应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的。

反转:程序本身不创建对象,而是变成被动的接受对象

依赖注入:就是利用set方法来进行注入的

2.3 IOC创建对象的方式

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

实体类:

private String str;
public String getStr() {
    return str;
}
public void setStr(String str) {
    this.str = str;
}
@Override
public String toString() {
    return "Hello{" +
            "str='" + str + '\'' +
            '}';
}
<bean id="hello" class="com.smile.pojo.Hello">
    <property name="str" value="Spring"/>
</bean>

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

实体类:

public class User {
    private String name;
    public User(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}
<!--有参构造:下标复制-->
<bean id="user" class="com.smile.pojo.User">
    <constructor-arg index="0" value="贾富荣"/>
</bean>

3.使用类型创建对象,不建议使用

<!--通过类型创建,不建议使用-->
<bean id="user1" class="com.smile.pojo.User">
    <constructor-arg type="java.lang.String" value="jiafurong"/>
</bean>

4.直接通过参数名使用 建议使用

<!--直接通过参数名-->
<bean id="user2" class="com.smile.pojo.User">
    <constructor-arg name="name" value="fengyanqiu"/>
</bean>

总结:在配置文件加载的时候,容器中管理的对象就已经初始化了(也就是beans.xml中ApplicationContext)

3.Spring的配置

3.1 别名 建议使用name

<!--直接通过参数名-->
<bean id="user2" class="com.smile.pojo.User">
    <constructor-arg name="name" value="fengyanqiu"/>
</bean>
<alias name="user2" alias="inputNameoK"/>
@Test
public void test4(){
    //获取spring的上下文对象
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    //我们的对象现在都在Spring中的管理了,我们要使用,直接去里面取出来就可以了
    Object user = context.getBean("inputNameoK"); //user2 都可以
    System.out.println(user);
}

3.2 Bean的配置

<!--
id:bean的唯一标识符,也就是相当于我们学的对象名
class:bean对象所对应的全限定名  : 包名+类型
name:也是别名,而且name可以多个,分割方式也多个  推荐贾富荣使用
-->
<bean id="userO" class="com.smile.pojo.Hello" name="name1,name2,name3 name4;name5">
    <property name="str" value="西部计划"/>
</bean>

3.3 import

import一般用于团队开发使用,它可以将多个配置文件,导入合并为一个,使用的时候直接使用总的配置就可以了。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IveUn6p2-1640586044509)(E:\Typroa笔记\Spring.assets\image-20211130182034951.png)]

注意:子文件可以重复,但是会合并,并不会报错

4 DI依赖注入(Dependency Injection)

4.1 构造器注入

​ 第二章知识点

​ c-namespace类似 必须constructor-arg elements

4.2 set方式注入【重点】

  • 依赖注入
    • 依赖:bean对象的创建依赖于容器
    • 注入:bean对象中的所有属性,由容器来注入
    • p-namespace类似

【环境搭建】

  1. pojo层

    package com.smile.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='" + address + '\'' +
                    '}';
        }
    }
    
    package com.smile.pojo;
    import java.util.*;
    public class Student {
        private String name;
        private Address address;
        private String[] books;
        private List<String> hobbys;
        private Map<String,String> card;
        private Set<String> games;
        private String wife;
        private Properties info;
    
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Address getAddress() {
            return address;
        }
        public void setAddress(Address address) {
            this.address = address;
        }
        public String[] getBooks() {
            return books;
        }
        public void setBooks(String[] books) {
            this.books = books;
        }
        public List<String> getHobbys() {
            return hobbys;
        }
        public void setHobbys(List<String> hobbys) {
            this.hobbys = hobbys;
        }
        public Map<String, String> getCard() {
            return card;
        }
        public void setCard(Map<String, String> card) {
            this.card = card;
        }
        public Set<String> getGames() {
            return games;
        }
        public void setGames(Set<String> games) {
            this.games = games;
        }
        public String getWife() {
            return wife;
        }
        public void setWife(String wife) {
            this.wife = wife;
        }
        public Properties getInfo() {
            return info;
        }
        public void setInfo(Properties info) {
            this.info = info;
        }
        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", address=" + address.toString() +
                    ", books=" + Arrays.toString(books) +
                    ", hobbys=" + hobbys +
                    ", card=" + card +
                    ", games=" + games +
                    ", wife='" + wife + '\'' +
                    ", info=" + info +
                    '}';
        }
    }
    
  2. resource层applicationContext.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">
    
        <bean id="address" class="com.smile.pojo.Address">
            <property name="address" value="这是地址"/>
        </bean>
        <!--第一种 普通值注入,value-->
        <bean id="student" class="com.smile.pojo.Student">
            <property name="name" value="贾富荣"/>
            <!--第二种  Bean注入  ref-->
            <property name="address" ref="address"/>
            <!--数组注入  ref-->
            <property name="books">
                <array>
                    <value>红楼梦</value>
                    <value>西游记</value>
                    <value>水浒传</value>
                    <value>三国演义</value>
                </array>
            </property>
    
            <!--List-->
            <property name="hobbys">
                <list>
                    <value>唱歌</value>
                    <value>跳舞</value>
                    <value>睡觉</value>
                </list>
            </property>
    
            <!--Map-->
            <property name="card">
                <map>
                    <entry key="idcard" value="62282618888888888888"/>
                    <entry key="idbank" value="11111111111111111111"/>
                    <entry key="id" value="222222222222222222222222"/>
                </map>
            </property>
            <!--Set-->
            <property name="games">
                <set>
                    <value>LOL</value>
                    <value>BOB</value>
                </set>
            </property>
            <!--Null / empty-->
            <property name="wife" value="">
            </property>
            <!--<property name="wife">
                <null/>
            </property>-->
            <!--Properties  配置文件
            key=value
            -->
            <property name="info">
                <props>
                    <prop key="学号">202111111</prop>
                    <prop key="性别"></prop>
                    <prop key="姓名">小米</prop>
                    <prop key="username">root</prop>
                    <prop key="password">111111</prop>
                </props>
            </property>
        </bean>
    </beans>
    
  3. Junit层

    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student)context.getBean("student");
        System.out.println(student);
        控制台打印的值
        //Student{name='贾富荣',
        // address=Address{address='这是地址'},
        // books=[红楼梦, 西游记, 水浒传, 三国演义], hobbys=[唱歌, 跳舞, 睡觉],
        // card={idcard=62282618888888888888, idbank=11111111111111111111, id=222222222222222222222222},
        // games=[LOL, BOB],
        // wife='',
        // info={学号=202111111, 性别=男, password=111111, 姓名=小米, username=root}}
    }
    

4.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">

    <!--p-namespace注入,可以直接注入属性的值-->
    <bean id="user" class="com.smile.pojo.User" p:age="19" p:name="贾富荣"/>
    <!--c-namespace注入,通过构造器注入:construct-args:-->
    <bean id="user2" class="com.smile.pojo.User" c:age="21" c:name="冯艳秋"/>
</beans>

测试:

/**
 * p-namespace p命名空间注入,可直接注入属性的值:property
 * c-namespace注入,通过构造器注入:construct-args:
 */
@Test
public void Ptest(){
    ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
    User user = context.getBean("user2",User.class);
    System.out.println(user);
}

注意点:p命名和c命名空间不能直接使用,需要导入xml约束

4.4 Bean的作用域

ScopeDescription
singleton(Default) Scopes a single bean definition to a single object instance for each Spring IoC container.
prototypeScopes a single bean definition to any number of object instances.
requestScopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
sessionScopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
applicationScopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
websocketScopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.
4.4.1 代理模式(Spring默认机制)
<bean id="user2" class="com.smile.pojo.User" c:age="21" c:name="冯秋" scope="singleton"/>
4.4.2 原型模式:每次从容器中get的时候,都会产生一个新对象!‘
<bean id="user" class="com.smile.pojo.User" p:age="19" p:name="贾富荣" scope="prototype"/>

5 Bean的自动装配

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

在Spring中有三种装配的方式

1.在xml中显示的配置

2.在java中显示的配置

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

5.1 ByName和ByType自动装配

环境搭建:一人两宠物

<bean id="cat" class="com.smile.pojo.Cat"/>
<bean id="dog" class="com.smile.pojo.Dog"/>
<!--autowire:
byName: 会自动在容器上下文中查找,和自己对象Person实体类中Set方法后面的值对应的beanid!
byType: 会自动在容器上下文中查找,和自己对象属性类型相同的bean
-->
<bean id="person" class="com.smile.pojo.Person" autowire="byName">
    <property name="name" value="贾富荣"/>
</bean>

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

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

5.2 使用注解实现自动装配

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

The introduction of annotation-based configuration raised the question of whether this approach is “better” than XM

要使用注解须知:

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/>

</beans>

@Autowired

直接在属性上使用即可!也可以在set方法上使用!

使用Autowired我看可以不用编写Set方法了,前提是这个自动装配的属性IOC (Spring)容器中存在,且符合buName命名规则

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

测试代码

 @Autowired(required = false)   //显性的定义了Autowired的required属性为false,说明这个对象可以为null,否则不能为空
  private Cat cat;

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

public class Person {

    @Autowired
    @Qualifier(value = "cat")
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog")
    private Dog dog;
    private String name;

Autowired通过类似于byName,如果存在多个,则会导致失败,所以和Qualifier使用

@Resource

import javax.annotation.Resource;
public class Person {
    @Resource( name = "cat")
    private Cat cat;
    @Resource
    private Dog dog;
    private String name;

小结

@Resource和@Autowired的区别:

  • 都是用来自动装配的,都可以放在属性字段上
  • @Autowired 通过byType的方式实现,而且必须要求这个对象存在!【常用】
  • @Resource 默认通过byName的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下,会报错!
  • 执行顺序不同:@Autowired 通过byType方式实现!@Resource 默认通过byName的方式实现

6 使用注解进行开发

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uSTblV8S-1640586044510)(E:\Typroa笔记\Spring.assets\image-20211201172556392.png)]

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

6.1 Bean
6.2 属性如何注入
//等价于:<bean id="user" class="com.smile.pojo.User"/>
//@Component  组件
@Component
public class User {

    //相当于 <property name = "name" value="贾富荣"/>
    @Value("贾富荣")   //也可以放在set方法上面
    public String name;
}
6.3 衍生的注解

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

  • dao 【@Repository】

  • service 【@Service】

  • controller 【@Controller】

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

6.4 作用域
package com.smile.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
//等价于:<bean id="user" class="com.smile.pojo.User"/>
//@Component  组件
@Component
@Scope("prototype")
public class User {

    //相当于 <property name = "name" value="贾富荣"/>
    @Value("贾富荣")   //也可以放在set方法上面
    public String name;
}

小结

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

xml 与 注解最佳实践:

  • xml用来管理bean
  • 注解值负责完成属性注入
  • 我们在使用的过程中,只需要注意一个问题,必须让注解生效,就需要开启注解的支持

7 使用Java的方式配置Spring

我们现在要完全不使用Spring的xml配置了,全权交给Java来做!

JavaConfig是Spring的一个子项目,在Spring4之后,它称为了一个核心功能

实体类:

//这里这个注解的意思,就是说明这个类被Spring接管了,注册到了容器中
@Component
public class User {
    @Value("贾富荣")
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}
//AppConfig配置类
package com.smile.config;

import com.smile.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration   //代表一个配置类,相当于beans标签,这个也会被Spring容器托管,注册到容器中,因为它本来就是一个@Component
@ComponentScan("com.smile.pojo")
@Import(AppConfig2.class)  //引入其他bean类
public class AppConfig {
    //注册一个bean,就相当于xml中的一个bean标签
    //这个方法的名字,就相当于bean标签中的id属性
    //这个方法的返回值,就相当于bean标签中的class属性

    @Bean    //相当于Bean标签
    public User getUser(){
        return new User();//返回要注入到bean的对象
    }
}
@Test
public void test1(){
    //通过纯注解的方式实现
    //如果完全使用了配置类方式去做,我们就只能通过AnnotationConfigApplicationContext上下文来获取容器,通过配置类的class对象加载
    ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
    User getUser = (User) context.getBean("getUser");
    System.out.println(getUser.getName());
}

8. 代理模式

SpringAOP的底层。面向切面编程的底层实现,就是代理模式!

8.1 静态代理

租房->中介->房东

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0Kbo4uEG-1640586044511)(E:\Typroa笔记\Spring.assets\image-20211202122942648.png)]

角色分析:

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

代理步骤:

1.接口

//租房
public interface Rent {
    public void rent();
}

2.真实角色

//房东
public class Host implements Rent{
    public void rent() {
        System.out.println("房东要出租房子");
    }
}

3.代理角色

package com.smile.demo1;
public class Proxy implements Rent{
    private Host host;
    public Proxy() {
    }
    public Proxy(Host host) {
        this.host = host;
    }
    //代理事情
    public void rent() {
        seeHost();
        host.rent();
        fare();
    }
    //中介独有 ,拓展
    public void seeHost(){
        System.out.println("带你看房子");
    }
    //收中介费
    public void fare(){
        System.out.println("收中介费");
    }
}

4.客户端访问代理角色

//我租房子
public class Client {
    public static void main(String[] args) {
        //房东要租房子
        Host host = new Host();
        //代理,中介帮房东租房子,但是呢? 代理一般会有一些附属操作
        Proxy proxy = new Proxy(host);
        //你不用面对房东,直接找中介租房即可
        proxy.rent();
    }
}
代理模式的好处:
  • 可以使真实角色的操作更加纯粹,不用去关注一些公共的业务
  • 公共也就交给代理角色!实现业务的分工
  • 公共业务发生扩展的时候,方便管理

缺点:

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

8.1.1 模仿业务操作

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-j2eOhoZX-1640586044513)(E:\Typroa笔记\Spring.assets\image-20211202133837905.png)]

在原有代码基础上,新增加代码,不改变原先业务

1.接口

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

2.真实角色

//真实对象
public class UserServiceImpl implements UserService{
    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 UserServiceProxy implements UserService{
    private UserServiceImpl userService;
    public void setUserService(UserServiceImpl userService) {
        this.userService = userService;
    }
    public void add() {
        log("add");
        userService.add();
    }
    public void delete() {
        log("delete");
        userService.delete();
    }
    public void update() {
        log("update");
        userService.update();
    }
    public void query() {
        log("query");
        userService.query();
    }
    //日志方法
    public void log(String msg){
        System.out.println("使用了:"+msg+"方法");
    }
}

4.客户端访问代理角色

public class Client {
    public static void main(String[] args) {
        UserServiceImpl userService = new UserServiceImpl();
        UserServiceProxy userServiceProxy = new UserServiceProxy();
        userServiceProxy.setUserService(userService);
        userServiceProxy.add();
    }
}

8.2 动态代理

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

动态代理模式的优势

  • 可以使真实角色的操作更加纯粹,不用去关注一些公共的业务
  • 公共也就交给代理角色!实现业务的分工
  • 公共业务发生扩展的时候,方便管理
  • 一个动态代理类代理的是一个接口,一般就是对应的一类业务
  • 一个动态代理类可以代理多个类,只要是实现同一接口即可

Proxy代理

InvocationHandler:调用处理程序

1.接口

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

2.真实业务

//真实对象
public class UserServiceImpl implements UserService{
    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.动态代理生成(工具类)

package com.smile.demo4;

import com.smile.demo3.Rent;

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

//使用这个类自动生成代理类!
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());   //method反射很强大
        Object result = method.invoke(target, args);
        return result;
    }

    public void log(String msg){
        System.out.println("日志"+msg);
    }
}

4.客户端访问代理角色

import com.smile.demo2.UserService;
import com.smile.demo2.UserServiceImpl;

public class Client {
    public static void main(String[] args) {
        //真实角色
        UserServiceImpl userService = new UserServiceImpl();
        //代理角色,不存在
        ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();

        proxyInvocationHandler.setTarget(userService);  //设置要代理的对象
        //动态生成代理类
        UserService proxy = (UserService) proxyInvocationHandler.getProxy();
        proxy.delete();

    }
}

8.3使用Spring实现AOP

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

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.6</version>
</dependency>
方式一:使用Spring的API接口
<!--注册bean-->
<bean id="userService" class="com.smile.service.UserServiceImpl"/>
<bean id="log" class="com.smile.log.Log"/>
<bean id="afterLof" class="com.smile.log.AfterLof"/>

<!--方式一:使用原生Spring API接口-->
<!--配置AOP:需要导入aop的约束-->
<aop:config>
    <!--切入点:expression:表达式-  execution(要执行的位置 * * * * *)-->
    <aop:pointcut id="pointcut" expression="execution(* com.smile.service.UserServiceImpl.*(..))"/>

    <!--执行环绕增加-->
    <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
    <aop:advisor advice-ref="afterLof" pointcut-ref="pointcut"/>
</aop:config>

实现类:

public class AfterLof implements AfterReturningAdvice {
    //returnValue:返回值
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("execute method"+method.getName()+",return result is"+returnValue);
    }
}

测试:

@Test
public void testPointcut(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserService userService = (UserService) context.getBean("userService");
    userService.update();
}
方式二:自定义类来实现AOP【主要是切面定义】

实体类:

public class DiyPonitcut {
    public void before(){
        System.out.println("+++++++method before !");
    }
    public void after(){
        System.out.println("+++++method after!");
    }
}

接口:

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

实现:

public class UserServiceImpl implements UserService {

    public void add() {
        System.out.println("增加了一个用户");
    }
    public void delete() {
        System.out.println("删除了一个用户");
    }
    public void update() {
        System.out.println("更新了一个用户");
    }
    public void query() {
        System.out.println("查询了一个用户");
    }
}

测试:

@Test
public void testPointcut(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserService userService = (UserService) context.getBean("userService");
    userService.update();
    /*  +++++++method before !
        更新了一个用户
        +++++method after!
       */
}
方式三:使用注解实现AOP

applicationContext.xml:

<!--方式三-->
<bean id="annotationPointct" class="com.smile.diy.AnnotationPointct"/>
<!--开启注解自动支持-->
<aop:aspectj-autoproxy/>
package com.smile.diy;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

//使用注解方式实现AOP
@Aspect
public class AnnotationPointct {

    @Before("execution(* com.smile.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("++++method before++++");
    }
    @After("execution(* com.smile.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("++++=method after!======");
    }
    //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
    @Around("execution(* com.smile.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {

        Signature signature = joinPoint.getSignature();  //获得签名
        System.out.println(signature);
        //执行方法
        System.out.println("around before");
        Object proceed = joinPoint.proceed();
        System.out.println("around after");
    }
}

测试:

@Test
public void testPointcut(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserService userService = (UserService) context.getBean("userService");
    userService.update();
    /*void com.smile.service.UserService.update()
    around before
    ++++method before++++
    更新了一个用户
            ++++=method after!======
    around after*/
}

9 整合Mybatis

步骤:

  1. 导入相关jar包

    • junit
    • mybatis
    • mysql数据库
    • spring相关的
    • aop织入
    • mybatis-spring
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <parent>
            <artifactId>SpringDemo</artifactId>
            <groupId>org.example</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>spring-10-mybatis</artifactId>
    
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13.2</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.25</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.3.12</version>
            </dependency>
            <!--Spring操作数据库的话,还需要spring-jdbc-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.3.8</version>
            </dependency>
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.9.6</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>2.0.6</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.20</version>
            </dependency>
        </dependencies>
    
        //target没有生成UserMapper.xml
        <build>
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.*</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
            </resources>
        </build>
    
    </project>
    
  2. 编写配置文件

  3. 测试

9.1 Mybatis-spring

整合Mybatis方式一:

地址:http://mybatis.org/spring/zh/getting-started.html

1.编写数据源配置

2.sqlSessionFactory

3.sqlSessionTemplate

4.需要给接口加实现类【】

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

6.测试

整合Mybatis方式二

SqlSessionDaoSupport 是一个抽象的支持类,用来为你提供 SqlSession。调用 getSqlSession() 方法你会得到一个 SqlSessionTemplate,之后可以用于执行 SQL 方法

方式一和方式二代码:

实体类:对应数据库表

@Data
public class User {
    private int id;
    private String username;
    private String password;
}

接口:UserMapper

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

方式一:实现类:UserMapperImpl

import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

public class UserMapperImpl implements UserMapper{
    //之前,我们所以的操作都使用sqlSession来执行。现在都使用SqlSessionTemplate;
    private SqlSessionTemplate sqlSession;

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

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

方式二的实现类:UserMapperImpl2

import cpm.smile.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.List;

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

Sql:UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cpm.smile.mapper.UserMapper">
    <select id="selectUser" resultType="user">
        select * from db1.user;
    </select>
</mapper>

Resources:配置文件

主:applicationContext.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
        ">
    <import resource="spring-dao.xml"/>
    <!--方式一:-->
    <bean id="userMapper" class="cpm.smile.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
    <!--方式二:-->
    <bean id="userMapper2" class="cpm.smile.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>
</beans>

mybatis-cconfig.xml

<?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="cpm.smile.pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?
                        useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!--注意此处映射-->
    <!--<mappers>
        <package name="cpm.smile.mapper"/>
    </mappers>-->

</configuration>

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:tx="http://www.springframework.org/schema/tx"
       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/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
        ">
        <!--DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid
        这里使用Spring提供的JDBC
        -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/db1?
                        useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <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:cpm/smile/mapper/*.xml"/>
    </bean>


    <!--此处方式二不需要:-->
    <!--SqlSessionTemolate:就是我们使用的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">
        <constructor-arg ref="dataSource" />
        <!--类似于这个:<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="*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>

    <!--配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointcut" expression="execution(* cpm.smile.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>
</beans>

测试代码:

import cpm.smile.mapper.UserMapper;
import cpm.smile.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MyTest {
    @Test
    public  void test1() throws IOException {
        String resources = "mybatis-config.xml";
        InputStream input = Resources.getResourceAsStream(resources);

        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(input);
        SqlSession sqlSession = sessionFactory.openSession(true);

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.selectUser();
        for (User user:users
             ) {
            System.out.println(user);
        }
    }

    @Test
    public void test2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper",UserMapper.class);
        List<User> users = userMapper.selectUser();
        for (User user:users
        ) {
            System.out.println(user);
        }
    }

    /**
     * 方式二:使用SqlSessionDaoSupport
     */
    @Test
    public void test3(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper2",UserMapper.class);
        List<User> users = userMapper.selectUser();
        for (User user:users
        ) {
            System.out.println(user);
        }
    }
}

10 声明式事务

10.1 回顾事务
  • 把一组业务当成一个业务来做;要么都成功,要么都失败。
  • 事务在项目开发中,十分重要,涉及到数据的一致性问题,不能马虎。
  • 确保完整性和一致性

事务ACID原则:

  • 原子性(Atomicity):原子性是指事务是一个不可分割的工作单位,事务中的操作要么都发生,要么都不发生。
  • 一致性(Consistency):事务前后数据的完整性必须保持一致。
  • 隔离性(Isolation):事务的隔离性是多个用户并发访问数据库时,数据库为每一个用户开启的事务,不能被其他事务的操作数据所干扰,多个并发事务之间要相互隔离。
  • 持久性(Durability):持久性是指一个事务一旦被提交,它对数据库中数据的改变就是永久性的,接下来即使数据库发生故障也不应该对其有任何影响

**注意:**为什么需要事务?

  • 如果不配置事务,可能存在数据提交不一致的情况。
  • 如果Spring没有配置声明式事务,则需要在代码中手动配置事务!

附录

1. HelloSpring 项目

1.实体类

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='" + str + '\'' +
                '}';
    }
}

2.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--使用Spring来创建对象,在Spring这些都称为Bean
    类型 变量名 = new 类型();
    Hello hello = new Hello();
    id=变量名
    class=new 的对象
    property=相当于给对象中的属性设置一个值
    -->
    <bean id="hello" class="com.smile.pojo.Hello">
        <property name="str" value="Spring"/>
    </bean>
</beans>

3.测试

@Test
public void test1(){
    //获取spring的上下文对象
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    //我们的对象现在都在Spring中的管理了,我们要使用,直接去里面取出来就可以了
    Hello hello= (Hello)context.getBean("hello");
    System.out.println(hello.toString());
}
2.Spring User代码

1.dao接口

public interface UserDao {
    void getUser();
}
public class UserDaoImpl implements UserDao{
    public void getUser() {
        System.out.println("默认获取用户的数据");
    }
}

2.service接口

public interface UserService {
    void getUser();
}
public class UserServiceImpl implements UserService{
    private UserDao userDao;
    //利用set进行动态实现值的注入
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    public void getUser() {
     userDao.getUser();
    }
}

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

    <bean id="userImpl" class="com.smile.dao.UserDaoImpl"/>
    <bean id="sqlImpl" class="com.smile.dao.SqlDaoImpl"/>  <!--第二个接口代码-->

    <bean id="userServiceImpl" class="com.smile.service.UserServiceImpl">
        <!--ref:引用Spring容器中创建好的对象  value:具体的值,基本数据类型等-->
        <property name="userDao" ref="sqlImpl"/>  <!--此处只需修改ref引用-->
        //<property name="userDao" ref="userImpl"/>
    </bean>

</beans>

4.测试

@Test
public void test3(){
    //获取ApplicationContext:拿到Spring容器
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    //容器在手,需要那些取那些
    UserServiceImpl userServiceImpl = (UserServiceImpl)context.getBean("userServiceImpl");
    userServiceImpl.getUser();
}
3.注解说明

@Autowired :自动装配通过类型,名字。

​ 如果Autowired不能唯一自动装配上属性,则需要通过Qualifier(value=“xxx”)

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

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

@Component:组件.放在类上,说明这个类被Spring管理了,就是bean!

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

rService {

void getUser();

}


```java
public class UserServiceImpl implements UserService{
    private UserDao userDao;
    //利用set进行动态实现值的注入
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    public void getUser() {
     userDao.getUser();
    }
}

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

    <bean id="userImpl" class="com.smile.dao.UserDaoImpl"/>
    <bean id="sqlImpl" class="com.smile.dao.SqlDaoImpl"/>  <!--第二个接口代码-->

    <bean id="userServiceImpl" class="com.smile.service.UserServiceImpl">
        <!--ref:引用Spring容器中创建好的对象  value:具体的值,基本数据类型等-->
        <property name="userDao" ref="sqlImpl"/>  <!--此处只需修改ref引用-->
        //<property name="userDao" ref="userImpl"/>
    </bean>

</beans>

4.测试

@Test
public void test3(){
    //获取ApplicationContext:拿到Spring容器
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    //容器在手,需要那些取那些
    UserServiceImpl userServiceImpl = (UserServiceImpl)context.getBean("userServiceImpl");
    userServiceImpl.getUser();
}
3.注解说明

@Autowired :自动装配通过类型,名字。

​ 如果Autowired不能唯一自动装配上属性,则需要通过Qualifier(value=“xxx”)

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

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

@Component:组件.放在类上,说明这个类被Spring管理了,就是bean!

  • @Service service
  • @Controller controller
  • @Repository dao
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值