栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring教程

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring教程

Spring 1.介绍

官网:https://spring.io/

Spring 让每个人都可以更快、更轻松、更安全地编写 Java。Spring 对速度、简单性和生产力的关注使其成为世界上最受欢迎的Java 框架。

我们使用了 Spring 框架附带的许多工具,并获得了许多开箱即用的解决方案所带来的好处,并且不必担心编写大量额外的代码——这确实为我们节省了一些时间和能量。

2.特征
  • 核心技术:依赖注入、事件、资源、i18n、验证、数据绑定、类型转换、SpEL、AOP。
  • 测试:模拟对象、TestContext 框架、Spring MVC 测试、WebTestClient.
  • 数据访问:事务、DAO 支持、JDBC、ORM、编组 XML。
  • Spring MVC和 Spring WebFlux Web 框架。
  • 集成:远程处理、JMS、JCA、JMX、电子邮件、任务、调度、缓存。
  • 语言:Kotlin、Groovy、动态语言。
3.核心技术

IOC:控制反转,将对象的创建权交给了Spring去管理

DI:依赖注入,把数据给创建好的对象中的属性进行赋值

AOP:面向切面编程,底层是代理模式

4.Bean的创建

org.springframework.beans和org.springframework.context包是 Spring Framework 的 IoC 容器的基础。该 BeanFactory 接口提供了一种高级配置机制,能够管理任何类型的对象。 ApplicationContext 是 BeanFactory的子接口。它补充说:

  • 更容易与 Spring 的 AOP 功能集成
  • 消息资源处理(用于国际化)
  • 活动发布
  • 应用层特定上下文,例如WebApplicationContext 用于 Web 应用程序的上下文。

org.springframework.context.ApplicationContext接口代表 Spring IoC 容器,负责实例化、配置和组装 bean。

4.1无参构造创建

导入依赖



    
        org.springframework
        spring-context
        5.3.20
    
    
        junit
        junit
        4.13.2
        test
    

创建User实体类

package com.qf.pojo;


public class User {

    private Integer id;
    private String name;
    private String password;

    public User() {
        System.out.println("无参构造");
    }
}

编写applicationContext.xml配置文件




    
    
    


编写测试类

package com.qf.test;

import com.qf.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class SpringTest {

    @Test
    public void testUser() {
        //需要加载配置文件
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");

        //根据bean标签中的id属性值,获取bean对象
        User user = (User)applicationContext.getBean("user");

        System.out.println(user);

    }
}
4.2工厂创建

创建工厂类

package com.qf.factory;

import com.qf.pojo.User;


public class UserFactory {

    
    public User getUser() {
        //return new User();

        //反射 + 配置文件
        try {
            return  (User)Class.forName("com.qf.pojo.User").newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //return null;
        //手动抛异常
        throw new RuntimeException("创建User对象异常");
    }


    
    public static User getUserStatic() {
        //return new User();

        //反射 + 配置文件
        try {
            return  (User)Class.forName("com.qf.pojo.User").newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //return null;
        //手动抛异常
        throw new RuntimeException("创建User对象异常");
    }
}

配置applicationContext.xml




    



    



    
    


4.3简单工厂模式

Car

package com.qf.factorymode.simplefactory;


public interface Car {

    
    public void run();
}
package com.qf.factorymode.simplefactory;


public class BaoSJ  implements Car {
    @Override
    public void run() {
        System.out.println("保时捷在飞驰...");
    }
}
package com.qf.factorymode.simplefactory;


public class FaLL implements Car {
    @Override
    public void run() {
        System.out.println("法拉利在飞驰...");
    }
}
package com.qf.factorymode.simplefactory;


public class CarFactory {

    //提供创建保时捷的方法
    public static BaoSJ creatBaoSJ() {
        try {
            return (BaoSJ)Class.forName("com.qf.factorymode.simplefactory.BaoSJ").newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //提供创建法拉利的方法
    public static FaLL creatFaLL() {
        try {
            return (FaLL)Class.forName("com.qf.factorymode.simplefactory.FaLL").newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

测试

package com.qf.factorymode.simplefactory;


public class Test {
    public static void main(String[] args) {

        //创建对象,调用方法
        //BaoSJ baoSJ = new BaoSJ();
        BaoSJ baoSJ = CarFactory.creatBaoSJ();
        baoSJ.run();

        //创建对象,调用方法
        //FaLL faLL = new FaLL();
        FaLL faLL = CarFactory.creatFaLL();
        faLL.run();

    }
}
4.4抽象工厂模式

Car

package com.qf.factorymode.abstractfactory;


public interface Car {

    
    public void run();
}
package com.qf.factorymode.abstractfactory;


public class BaoSJ  implements Car {
    @Override
    public void run() {
        System.out.println("保时捷在飞驰...");
    }
}
package com.qf.factorymode.abstractfactory;


public class FaLL implements Car {
    @Override
    public void run() {
        System.out.println("法拉利在飞驰...");
    }
}

CarFactory

package com.qf.factorymode.abstractfactory;


public interface CarFactory {

    
    public Car createCar();

}
package com.qf.factorymode.abstractfactory;


public class BaoSJFactory implements CarFactory{
    
    @Override
    public Car createCar() {
        try {
            return (BaoSJ)Class.forName("com.qf.factorymode.abstractfactory.BaoSJ").newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
package com.qf.factorymode.abstractfactory;


public class FaLLFactory implements CarFactory{
    @Override
    public Car createCar() {
        try {
            return (FaLL)Class.forName("com.qf.factorymode.abstractfactory.FaLL").newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

测试

package com.qf.factorymode.abstractfactory;


public class Test {
    public static void main(String[] args) {

        //创建对象,调用方法
        BaoSJFactory baoSJFactory = new BaoSJFactory();
        Car baoSJ = baoSJFactory.createCar();
        baoSJ.run();

        //创建对象,调用方法
        FaLLFactory faLLFactory = new FaLLFactory();
        Car faLL = faLLFactory.createCar();
        faLL.run();

    }
}
5.Bean的作用范围 5.1scope属性

bean标签的scope属性:指定当前bean的作用范围

取值:

singleton:单例( 默认值 )

prototype:多例

request:作用于Web应用的请求范围

session:作用于Web应用的会话范围

global-session:作用于集群环境Web应用的会话范围(全局会话)




5.2单例模式-懒汉式
package com.qf.singletonmode;


public class SingletonLazy {

    //构造器私有化
    private SingletonLazy() {}

    //声明对象
    private static SingletonLazy singletonLazy = null;

    //实例化,线程安全
    public static synchronized SingletonLazy getSingletonLazy() {
        //判断
        if(null == singletonLazy) {
            singletonLazy = new SingletonLazy();
        }

        return singletonLazy;
    }

}
5.3单例模式-饿汉式
package com.qf.singletonmode;


public class SingletonHungry {

    //私有化构造器
    private SingletonHungry() {}

    //实例化
    private static SingletonHungry singletonHungry = new SingletonHungry();

    //方法
    public static SingletonHungry getSingletonHungry() {
        return singletonHungry;
    }
}
5.4单例模式-双重校验锁
package com.qf.singletonmode;


public class SingletonLock {

    //构造器私有化
    private SingletonLock() {}

    //声明
    private static SingletonLock singletonLock = null;

    //实例化方法
    public static SingletonLock getSingletonLock() {
        //先检查当前实例是否为空,如果不存在再进行同步
        if(null == singletonLock){
            //同步
            synchronized (SingletonLock.class) {
                //再次检查当前实例是否为空
                if(null == singletonLock){
                    //返回
                    singletonLock = new SingletonLock();
                }
            }
        }
        return singletonLock;
    }
}
6.Bean生命周期



package com.qf.pojo;


public class User {

    private Integer id;
    private String name;
    private String password;

    public User() {
        System.out.println("无参构造");
    }

    
    public void initUser() {
        System.out.println("User 初始化方法");
    }

    
    public void destroyUser() {
        System.out.println("User 销毁方法");
    }

}

测试

@Test
public void testLife() {
    //创建ClassPathXmlApplicationContext对象
    ClassPathXmlApplicationContext applicationContext
        = new ClassPathXmlApplicationContext("applicationContext.xml");

    //获取对象
    User user = (User) applicationContext.getBean("user");

    System.out.println(user);

    //关闭
    applicationContext.close();
}
7.依赖注入

DI:Dependency Injection:给创建对象中的属性赋值

IOC作用:降低程序间耦合(依赖关系)

依赖关系维护:以后都交给Spring进行管理

可注入类型:

基本数据类型以及包装类

String类

类类型( 其他Bean类型 )

复杂类型:集合,数组…

7.1set方法注入

applicationContext.xml配置文件




    
    
        
        
    
    
    
        
        
        
        
        
    


实体类

package com.qf.pojo;

import lombok.Data;

@Data
public class Car {

    private Integer cid;
    private String cname;

}
package com.qf.pojo;

import lombok.Data;

@Data
public class User {

    private Integer id;
    private String name;
    private String password;

    private Car car;
}

测试

package com.qf.test;

import com.qf.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class SpringTest {

    @Test
    public void testUser(){

        //加载配置文件
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");

        //创建Bean
        User user =(User)applicationContext.getBean("user");

        //输出
        System.out.println(user);
    }
}
7.2复杂类型注入

1.注入数组对应的标签:array

2.注入LIst以及Set集合的标签:list,set

3.注入Map以及Propertis的标签:map,properties

创建实体类CollectionVo

package com.qf.vo;

import lombok.Data;

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


@Data
public class CollectionVo {

    private Integer [] arr;
    private List list;
    private Set set;
    private Map map;
    private Properties properties;

}

在applicationContext.xml文件中添加内容



    
    
        
            123
            456
            789
        
    

    
    
        
            jack
            jack
            rose
            
        
    

    
    
        
            张三
            张三
            李四
            
        
    

    
    
        
            
            
        
    

    
    
        
            root
            root
            jdbc:mysql:///db_name?serverTimezone=Asia/Shanghai
            com.mysql.cj.jdbc.Driver
        
    


测试

@Test
public void testCollectionVo() {

    //加载配置文件
    ApplicationContext applicationContext =
        new ClassPathXmlApplicationContext("applicationContext.xml");

    //创建Bean
    CollectionVo collectionVo = (CollectionVo) applicationContext.getBean("collectionVo");

    //输出
    System.out.println(collectionVo);
}
7.3构造器注入( 不常用 )

创建Car

package com.qf.pojo;

import lombok.Data;

@Data
public class Car {

    private Integer cid;
    private String cname;

    public Car(Integer cid, String cname) {
        this.cid = cid;
        this.cname = cname;
    }
}

创建User

package com.qf.pojo;

import lombok.Data;

@Data
public class User {

    private Integer id;
    private String name;
    private String password;

    private Car car;

    public User(Integer id, String name, String password, Car car) {
        this.id = id;
        this.name = name;
        this.password = password;
        this.car = car;

        System.out.println("第一个构造器");
    }

    
    public User(String name, Integer id,String password, Car car) {
        this.id = id;
        this.name = name;
        this.password = password;
        this.car = car;

        System.out.println("第二个构造器");
    }
}

配置applicationContext.xml文件




    
    
    
        
        
        
    

    
    
        
        
        
        
    

    
    
        
        
        
        
    


测试

package com.qf.test;

import com.qf.pojo.Car;
import com.qf.pojo.User;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {

    @Test
    public void testCar() {

        ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");

        Car car = (Car) applicationContext.getBean("firstCar");

        System.out.println(car);
    }

    @Test
    public void testUser() {

        ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");

        User user1 = (User) applicationContext.getBean("user1");
        System.out.println(user1);

        User user2 = (User) applicationContext.getBean("user2");
        System.out.println(user2);
    }
}
7.4注解注入

注意:需要在applicationContext.xml文件中,导入context约束

Car

package com.qf.pojo;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;


//@Component("myCar")
@Component
@Data
public class Car {

    @Value("20001")
    private Integer cid;

    //@Value("保时捷")
    private String cname;

    @Value("保时捷")
    public void setCname(String cname) {
        this.cname = cname;
    }
}

User

package com.qf.pojo;

import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;


@Component
@Scope(value = "singleton")
@Data
public class User {

    @Value("1001")
    private Integer id;

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

    @Value("123")
    private String password;

    
    @Autowired
    @Qualifier("otherCar")
    //@Resource(name = "otherCar")
    private Car car;


    
    @PostConstruct
    public void init(){
        System.out.println("User 初始化");
    }

    
    @PreDestroy
    public void destroy(){
        System.out.println("User 销毁");
    }
}

applicationContext.xml配置文件


 

        
        

        
        
                
                
        


bean.xml


 

        
        


测试

package com.qf.test;

import com.qf.pojo.Car;
import com.qf.pojo.User;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {

    
    @Test
    public void testCar() {

        ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");

        Car car = (Car) applicationContext.getBean("car");

        System.out.println(car);
    }

    
    @Test
    public void testUser() {

        ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");

        User user = (User) applicationContext.getBean("user");

        System.out.println(user);
    }

    
    @Test
    public void testScope() {

        ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");

        User user1 = (User) applicationContext.getBean("user");
        User user2 = (User) applicationContext.getBean("user");

        System.out.println(user1 == user2);
    }

    
    @Test
    public void testLife() {

        //通过其他配置文件测试
        ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("bean.xml");

        User user = (User) applicationContext.getBean("user");
        System.out.println(user);

        //关闭
        applicationContext.close();
    }

}
8.整合MyBatis 【重点】 8.1导入依赖


    4.0.0

    com.qf
    spring-05
    1.0-SNAPSHOT

    
        8
        8
    

    
        
        
            org.mybatis
            mybatis
            3.5.9
        

        
            mysql
            mysql-connector-java
            8.0.29
        

        
            com.alibaba
            druid
            1.2.9
        

        
            org.projectlombok
            lombok
            1.18.24
        

        
            log4j
            log4j
            1.2.17
        

        
        
            org.springframework
            spring-context
            5.3.20
        
        
        
            org.springframework
            spring-jdbc
            5.3.20
        
        
        
            org.mybatis
            mybatis-spring
            2.0.7
        

        
        
            junit
            junit
            4.13.2
            test
        


    


8.2User类
package com.qf.pojo;

import lombok.Data;

@Data
public class User {

    private Integer id;
    private String name;
    private String password;

}
8.3UserController
package com.qf.controller;


import com.qf.pojo.User;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.List;


@Controller
public class UserController {

    
    @Autowired
    private UserService userService;

    
    public List findAll(){
        return userService.findAll();
    }

}
8.4UserService
package com.qf.service;

import com.qf.pojo.User;

import java.util.List;

public interface UserService {
    
    List findAll();
}
8.5UserServiceImpl
package com.qf.service.impl;

import com.qf.mapper.UserMapper;
import com.qf.pojo.User;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class UserServiceImpl implements UserService {

    
    @Autowired
    private UserMapper userMapper;

    
    @Override
    public List findAll() {
        return userMapper.findAll();
    }
}
8.6UserMapper
package com.qf.mapper;

import com.qf.pojo.User;
import org.springframework.stereotype.Repository;

import java.util.List;


@Repository
public interface UserMapper {

    
    List findAll();
}
8.7UserMapper.xml




   
    
    
        
        
        
    
    
    
    
        select id, name, password from t_user
    
    
    
    
    

8.8db.properties
db.username = root
db.password = root
db.url = jdbc:mysql://localhost:3306/java2203?serverTimezone=Asia/Shanghai&characterEncoding=UTF8
db.driver = com.mysql.cj.jdbc.Driver
8.9log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
8.10mybatis-config.xml




    
    
        
    


8.11applicationContext.xml

 

        
        

        
        
            
            
            
            
            
        

        
        

        
        
            
            
            
            
            
            
             userList = userController.findAll();

        System.out.println(userList);
    }
}
9.数据源配置类

用于替换applicationContext.xml中数据源的相关配置

package com.qf.config;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.qf.pojo.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
import java.util.Properties;


@Configuration
@PropertySource(value = "classpath:db.properties")
public class DataSourceConfig {

    @Value("${db.username}")
    private String username;

    @Value("${db.password}")
    private String password;

    @Value("${db.url}")
    private String url;

    @Value("${db.driver}")
    private String driverClassName;

    
    @Bean("datasource")
    public DataSource getDataSource() {
        //设置数据源参数
        Properties properties = new Properties();
        properties.setProperty("username", username);
        properties.setProperty("password", password);
        properties.setProperty("url", url);
        properties.setProperty("driverClassName", driverClassName);

        DataSource dataSource = null;

        try {
            //创建数据源对象
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //返回
        return dataSource;
    }

}
10.分页 10.1导入依赖

    com.github.pagehelper
    pagehelper
    5.3.0

10.2第一种方式在mybatis-config.xml中配置




    
    
        
    

    
    
        
        
            
            
            
            
            
            
        
    


10.3第二种方式在applicationContext.xml中配置
 

    
    
    
    
    
    
     
9.AOP 

Aspect Oriented Programing 面向切面编程

springAOP:在程序运行期通过动态代理的方式向目标类(接口),织入增强的代码,为目标类(接口)中的方法添加额外的功能

采取是横向抽取机制,取代了我们传统的纵向继承方式重复性的代码

底层原理:代理模式

9.1装饰器模式

装饰器模式:对象本身增强

代理模式:代理对象(代理过程)增强

9.1.1Info
package com.qf.decorator;


public abstract class Info {

    
    public abstract void info();

}
9.1.2PersonInfo
package com.qf.decorator;


public class PersonInfo extends Info{
    @Override
    public void info() {
        System.out.println("自我介绍");
    }
}
9.1.3Decorator
package com.qf.decorator;


public abstract class Decorator extends Info{

    private Info info;

    //传入被装饰对象
    public Decorator(Info info){
        this.info = info;
    }

    @Override
    public void info() {
        //调用自我介绍的方法
        info.info();
    }
}
9.1.4Singer
package com.qf.decorator;


public class Singer extends Decorator{

    //调用父类构造器
    public Singer(Info info) {
        super(info);
    }

    //自己的方法
    public void singing(){
        System.out.println("唱歌");
    }

    //重写方法,达到增强的目的
    @Override
    public void info() {
        super.info();
        singing();
    }
}
9.1.5Dancer
package com.qf.decorator;


public class Dancer extends Decorator{

    public Dancer(Info info) {
        super(info);
    }

    public void dancing(){
        System.out.println("跳舞");
    }

    @Override
    public void info() {
        super.info();
        dancing();
    }
}
9.1.6Magic
package com.qf.decorator;


public class Magic extends Decorator{

    public Magic(Info info) {
        super(info);
    }

    public void magic(){
        System.out.println("变魔术");
    }

    @Override
    public void info() {
        super.info();
        magic();
    }
}
9.1.7测试
package com.qf.decorator;

public class Test {
    public static void main(String[] args) {

        //单独测试
//        Info personInfo = new PersonInfo();
//        personInfo.info();
//        System.out.println("----------------------");
//
//        Decorator singer = new Singer(personInfo);
//        singer.info();
//        System.out.println("----------------------");
//
//        Dancer dancer = new Dancer(personInfo);
//        dancer.info();
//        System.out.println("----------------------");


        //增强测试
        Info personInfo = new PersonInfo();
        Decorator singer = new Singer(personInfo);//第一次增强
        Dancer dancer = new Dancer(singer);//第二次增强
        Magic magic1 = new Magic(dancer);//第三次增强
        Magic magic2 = new Magic(magic1);//第四次增强

        magic2.info();
    }
}
9.2代理模式

通过代理类对象,为目标类对象添加功能

分类:静态代理和动态代理

静态代理:需要实现接口中的方法,进行增强,代理的功能代码有冗余,维护性较差

动态代理:在不实现接口中所有方法,对接口中的指定的方法进行增强

9.2.1静态代理

Rent

package com.qf.proxy.demo1;


public interface Rent {

    //出租房子
    public void rent();

    //其他的方法
    //public void test();
}

Owner

package com.qf.proxy.demo1;


public class Owner implements Rent{
    @Override
    public void rent() {
        System.out.println("房东出租房子");
    }
}

OwnerProxy

package com.qf.proxy.demo1;


public class OwnerProxy implements Rent{

    //房东对象
    private Owner owner;

    public OwnerProxy(Owner owner) {
        this.owner = owner;
    }

    public void publish(){
        System.out.println("发布租房信息");
    }

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

    @Override
    public void rent() {
        publish();
        owner.rent();
        seeHouse();
    }
}

测试

package com.qf.proxy.demo1;

public class Test {
    public static void main(String[] args) {

        Owner owner = new Owner();
        owner.rent();

        System.out.println("----------------");

        OwnerProxy ownerProxy = new OwnerProxy(owner);
        ownerProxy.rent();

    }
}
9.2.2动态代理

分为:JDK动态代理 和 CGLIB动态代理

JDK动态代理:基于接口的动态代理,被代理对象必须实现接口

CGLIB动态代理 :基于子类的动态代理,对目标对象进行继承代理

JDK动态代理

Rent

package com.qf.proxy.demo2;


public interface Rent {

    //出租房子
    public void rent();

    //其他的方法
    public void test();
}

Owner

package com.qf.proxy.demo2;


public class Owner implements Rent {
    @Override
    public void rent() {
        System.out.println("房东出租房子");
    }

    @Override
    public void test() {
        System.out.println("测试方法");
    }
}

RentJdkProxy

package com.qf.proxy.demo2;

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


public class RentJdkProxy implements InvocationHandler {

    private Rent rent;

    public void setRent(Rent rent) {
        this.rent = rent;
    }

    //生成代理对象
    public Rent getRent(){
        return (Rent)Proxy.newProxyInstance(
                rent.getClass().getClassLoader(), //类加载器
                rent.getClass().getInterfaces(),//接口列表
                this
        );
    }

    //对接口中的方法进行增强(扩展),不需要实现接口中的所有方法
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //声明变量做为方法的返回值
        Object result = null;

        //判断方法名,对其进行增强
        if("rent".equals(method.getName())){
            publish();
            result = method.invoke(rent,args);
            seeHouse();
        } else {
            result = method.invoke(rent,args);
        }

        return result;
    }


    public void publish(){
        System.out.println("发布租房信息");
    }

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

测试

package com.qf.proxy.demo2;

public class Test {
    public static void main(String[] args) {

        Owner owner = new Owner();
        owner.rent();

        System.out.println("-------------------");

        //创建RentJdkProxy对象
        RentJdkProxy rentJdkProxy = new RentJdkProxy();
        //给属性赋值
        rentJdkProxy.setRent(owner);

        //获取代理对象
        Rent proxyRent = rentJdkProxy.getRent();
        proxyRent.rent();

        proxyRent.test();

    }
}
9.3Spring中的AOP

面向切面编程 (AOP) 通过提供另一种思考程序结构的方式来补充面向对象编程 (OOP),OOP的延伸

对目标对象中的多个不同方法进行不同程度的增强

AOP的术语:
Joinpoint(连接点):所谓连接点是指那些被拦截到的点,在spring中,这些点指的是方法,spring只支持方法类型的连接点。
Pointcut(切入点):所谓切入点是指我们要对哪些Joinpoint进行拦截的定义。
Advice(通知/增强):所谓通知是指拦截到Joinpoint之后所要做的事情就是通知,通知分为前置通知,后置通知,异常通知,最终通知,环绕通知。
Introduction(引介):可以在运行期为类动态地添加一些方法或Field。
Target(目标对象):代理的目标对象。
Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程。
Proxy(代理):一个类被AOP织入增强后,就产生一个代理类。
Aspect(切面):是切入点和通知(引介)的结合

9.4XML配置AOP 9.4.1导入依赖

    
        org.springframework
        spring-context
        5.3.20
    

    
    
        org.aspectj
        aspectjweaver
        1.9.9.1
    

    
        junit
        junit
        4.13.2
        test
    


9.4.2UserService
package com.qf.service;


public interface UserService {

    //没有增强的方法,叫做连接点 JoinPoint
    //被增强的方法,叫做切入点 PointCut
    //增强的代码,叫做通知
    public void add();

    public void delete();

    public void update();

    public void query();
}
9.4.3UserServiceImpl
package com.qf.service.impl;

import com.qf.service.UserService;

public class UserServiceImpl implements UserService {
    @Override
    public void add() {
        System.out.println("add");
        int i = 1/0;//算数异常
    }

    @Override
    public void delete() {
        System.out.println("delete");
    }

    @Override
    public void update() {
        System.out.println("update");
    }

    @Override
    public void query() {
        System.out.println("query");
    }
}
9.4.4MyAdvice
package com.qf.advice;

import org.aspectj.lang.ProceedingJoinPoint;


public class MyAdvice {

    public void before(){
        System.out.println("前置通知,目标对象调用方法前执行");
    }

    public void after(){
        System.out.println("后置通知(最终通知),目标对象调用方法后执行,无论目标对象方法是否发生异常都会执行");
    }

    public void after_returning(){
        System.out.println("后置通知,目标对象调用方法后执行,目标对象方法发生异常则不执行");
    }

    public void after_throwing(){
        System.out.println("异常通知,目标对象调用方法发生异常时执行");
    }

    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕通知,目标对象调用方法之前");
        proceedingJoinPoint.proceed();
        System.out.println("环绕通知,目标对象调用方法之后");
    }

}
9.4.5applicationContext.xml

 


        
        

        
        


        
        
        
            

            

            
            
                
                

                
                

                
                

                
                

                
                

            

        


9.4.6测试
package com.qf.test;

import com.qf.service.UserService;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {

    @Test
    public void testAop(){

        ClassPathXmlApplicationContext applicationContext
                = new ClassPathXmlApplicationContext("applicationContext.xml");

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

        userService.add();

        //userService.delete();
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/894073.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号