SSM框架15 Spring的注解开发、Java方式配置spring、静态代理和动态代理、AOP、Spring整合mybatis、Spring的事务管理

一、Spring的注解开发

spring4之后进行注解开发,需要导入AOP包
1、导入AOP包
2、注解导入context约束

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       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:component-scan base-package="pojo"/>
    <context:annotation-config/>
</beans>
package pojo;

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

//Component注解 等价于<bean id="user" class="pojo.User"></bean>
@Component
public class User {
    @Value("kerwin")
//    Value注解 设置初始值 相当于property
    private String name;

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

component有许多衍生注解:

pojo		@Component
dao 		@Repository
service 	@Service
controller	@Controller

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

然后可以用@Autowired自动装配

可以用
@Scope("singleton") 设置作用域

二、xml和注解的区别

1、xml更加万能,适用于任何场合,维护起来简单方便
2、注解 不是自己类使用,维护相对复杂
3、xml用来管理bean
4、注解只负责完成属性的注入
5、使用注解的过程中,最需要注意的是,让注解生效,就需要开启注解的支持

三、使用java的方式配置Spring

也可以不依靠xml,用java来配置
JavaConfig是Spring的一个子项目,Spring4以后 成为核心功能

package config;

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

//类似于beans 核心配置文件
//这个也会被spring容器接管,注册到容器中,因为本身也是一个@Component
//代表一个配置类 类似bean.xml
@Configuration
//扫描pojo的包
@ComponentScan("pojo")
//合并多个配置类
@Import(MyConfig2.class)
public class MyConfig {
/*   注册一个bean 类似bean标签
    方法的名字类似bean标签的id
    方法的返回类型类似bean标签的class
    */
    @Bean
    User user(){
        return new User();
    }

}

import config.MyConfig;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import pojo.User;

public class TestDemo {
    @Test
    public void test1(){
//        如果使用了注释来配置 则只能通过AnnotationConfigApplicationContext来获取上下文获取容器
//        通过配置类的class对象加载
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User user = (User) context.getBean("user");
        System.out.println(user.toString());
    }
}

package pojo;

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

public class User {
    @Value("kerwin")
    private String name;

    public String getName() {
        return name;
    }

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

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

四、代理模式之静态代理

代理模式是SpringAOP的底层(SpringAOP和SpringMVC)
代理模式的分类:
1、静态代理
2、动态代理

简单说:有需要去找代理,代理不仅掌握了被代理对象的操作,自己还可以做拓展,用户有问题去找代理就行

代码步骤
1、接口
2、真实角色
3、代理角色
4、客户端访问代理角色

1、静态代理
角色分析:
①抽象角色:一般会使用接口或者抽象类来实现
②真实角色:被代理的角色
③代理角色:代理真实角色,代理真实角色后,一般会做一些附属操作
④客户:访问代理对象的人

代理模式的好处:

  • 可以使得真实角色的操作更加纯粹,不用去关注一些公共的业务
  • 公共业务交给代理角色,实现了业务的分工
  • 公共业务发生扩展的时候,方便集中管理
    缺点:
  • 一个真实角色就会产生一个代理角色,代码量翻倍,开发效率变低

五、代理模式之动态代理

动态代理和静态代理的角色一样
但是动态代理的代理类是动态生成的,不是直接静态写好的
动态代理分为两类:基于接口的动态代理和基于类的动态代理
①基于接口:JDK动态代理
②基于类:cglib
③java字节码实现:javassist

Proxy类和InvocationHandler类

动态代理的好处:

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

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

//当使用这类的时候 自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {
    private Object object;

    public void setObject(Object object) {
        this.object = object;
    }

    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),object.getClass().getInterfaces(),this );

    }

//    处理代理实例,并返回结果
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//        动态代理的本质是通过映射来实现的
        Object result = method.invoke(object, args);
        fare();
        return result;
    }

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

package demo;

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

package demo;

public class Client {
    public static void main(String[] args) {
        Host host = new Host();

        ProxyInvocationHandler pih = new ProxyInvocationHandler();
        pih.setObject(host);
//      这里的proxy是动态生成的
        Rent proxy = (Rent) pih.getProxy();

        proxy.rent();
    }
}

六、AOP实现

AOP即面向切面编程,面向对象的一种延续

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

横切关注点:跨越应用程序多个模块的方法和功能
切面:横切关注点被模块化的特殊对象,也就是个类
通知:切面必须要完成的工作,类中的方法
目标:被通知的对象
代理:向目标对象应用通知之后创建的对象
切入点:切面通知执行的地点的定义
连接点:与切入点匹配的执行点

1、使用AOP的依赖

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

2、方式一,使用Spring的API接口

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注册bean-->
    <bean id="userService" class="service.UserServiceImpl"/>
    <bean id="log" class="log.log"/>
    <bean id="afterLog" class="log.AfterLog"/>
<!--    配置aop 需要导入aop的约束 -->
    <aop:config>
<!--        切入点 -->
        <aop:pointcut id="pointcut" expression="execution(* service.UserServiceImpl.*(..))"/>
<!--        执行环绕增加-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>
</beans>
package log;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class log implements MethodBeforeAdvice {
    /**
     *
     * @param method    要执行的目标对象的方法
     * @param args      参数
     * @param target    目标对象
     * @throws Throwable
     */
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}

package log;

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

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

package service;

public class UserServiceImpl implements UserService{
    public void add() {
        System.out.println("add");
    }

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

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

    public void select() {
        System.out.println("select");
    }
}

package service;

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

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.UserService;
import service.UserServiceImpl;

public class MyTest {
    @Test
    public void test1(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//      动态代理 代理的是接口
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }

}

3、自定义来实现AOP

<!--    方式二 自定义类-->
    <bean id="diy" class="diy.DiyPointCut"/>
    <aop:config>
<!--        自定义切面 ref引用类-->
        <aop:aspect ref="diy" id="diy">
            <aop:pointcut id="point" expression="execution(* service.UserServiceImpl.*(..))"/>
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>
package diy;

public class DiyPointCut {

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

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

七、注解实现AOP

<!--    开启注解支持 proxy-target-class JDK(默认) true 使用cglib-->
    <aop:aspectj-autoproxy proxy-target-class="false"/>
package 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;
import org.springframework.stereotype.Component;

@Component
//方式三:注解实现AOP
@Aspect//标注这个类是一个切面
public class AnotationPointCut {
    @Before("execution(* service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("before1");
    }

    @After("execution(* service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("after1");
    }

    @Around("execution(* service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");
//        获取签名
        Signature signature = jp.getSignature();
        System.out.println(signature);
//        执行方法
        Object proceed = jp.proceed();

        System.out.println("环绕后");
        System.out.println(proceed);
    }
}

    @Test
    public void test3(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//      动态代理 代理的是接口
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }

八、spring整合mybatis框架

整合的官方文档:https://mybatis.org/spring/zh/index.html
需要导入mybatis-spring的依赖

<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/maven-v4_0_0.xsd">
    <parent>
        <artifactId>SpringDemo</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>Spring006</artifactId>
    <packaging>war</packaging>
    <name>Spring006 Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.31</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.22</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.24</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>





    </dependencies>
    <build>
        <finalName>Spring006</finalName>
    </build>
</project>

1、编写数据源配置
2、sqlSessionFactory
3、sqlSessionTemplate
4、需要给接口加实现类
5、将自己写的实现类,注入到Spring中
6、测试使用

①第一种方式

<?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的数据源替换mybatis配置  c3p0 dbcp druid
        Spring提供的JDBC-->
    <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?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.xml"/>
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
<!--    就是我们使用的sqlsession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--        只能构造器注入 因为没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
<!--导入映射文件-->
    <bean id="userMapper" class="mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
</beans>
<?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>
        <typeAlias type="pojo.User" alias="User"/>
    </typeAliases>

</configuration>
<?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.xml"/>
    <bean id="userMapper" class="mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
</beans>
@Test
    public void test2() throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapperImpl userMapper = context.getBean("userMapper", UserMapperImpl.class);
        for (User user : userMapper.selectUser()) {
            System.out.println(user.toString());
        }

    }

②第二种方式
SqlSessionDaoSupport 抽象类来直接获取sqlSession

    @Test
    public void test3() throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapperImpl userMapper = context.getBean("userMapper2", UserMapperImpl.class);
        for (User user : userMapper.selectUser()) {
            System.out.println(user.toString());
        }

    }
package mapper;

import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import pojo.User;

import java.util.List;

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{

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

<?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的数据源替换mybatis配置  c3p0 dbcp druid
        Spring提供的JDBC-->
    <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?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.xml"/>
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
<!--    就是我们使用的sqlsession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--        只能构造器注入 因为没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
</beans>
<?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.xml"/>
    <bean id="userMapper" class="mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
    <bean id="userMapper2" class="mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
</beans>

九、Spring的事务管理

要开启 Spring 的事务处理功能,在 Spring 的配置文件中创建一个 DataSourceTransactionManager 对象

REQUIRED:支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。

SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行。

MANDATORY:支持当前事务,如果当前没有事务,就抛出异常。

REQUIRES_NEW:新建事务,如果当前存在事务,把当前事务挂起。

NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。

NEVER:以非事务方式执行,如果当前存在事务,则抛出异常。

NESTED:支持当前事务,如果当前事务存在,则执行一个嵌套事务,如果当前没有事务,就新建一个事务。

如果不配置事务,可能会导致数据不一致
不再Spring中配置 则需要手动去配置

<!--        开启事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg ref="datasource"/>
    </bean>
<!--    结合AOP实现事务的织入 配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="select" propagation="REQUIRED"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
<!--    配置事务的切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值