学生程序设计能力提升平台源码分析(五)Service层源码分析

本文详细分析了Spring Service层的关键代码,包括@Service注解的使用、@Transactional事务管理的原理,以及实体类方法的作用。通过对这些核心概念的深入理解,有助于提升代码分析能力和程序设计水平。

前言

2021SC@SDUSC

概述

继第一次的项目概述,和二三四的Controller层源码分析,我们已经对关键代码的使用和其内部实现原理有了一定的了解,接下来将按照代码调用的流程,从Controller层过渡到Service层,这是因为在Controller层接受了请求之后,要调用Service层即服务层的服务进行处理,而不是直接进行数据操作,所以接下来几篇我们将重点放在Service层的关键代码以及其内部实现原理上

源码

源码如下:

@Service
public class BindService {
    @Autowired
    private BindMapper bindMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Transactional
    public Integer bindStuNum(StudentBind studentBind) throws DuplicateKeyException {
        if (UserUtil.getCurrentUserId() != null) {
            studentBind.setUserId(UserUtil.getCurrentUserId());
            if (bindMapper.validateStudentBind(studentBind) > 0) {
                roleMapper.insertRoleUserLink(studentBind.getUserId(), 3);
                UserInfo info = userInfoMapper.selectByUserId(UserUtil.getCurrentUserId());
                info.setStuNum(studentBind.getStuNum());
                info.setRealName(studentBind.getName());
                userInfoMapper.updateUserInfo(info);
                return 1;
            } else {
                return 0;
            }
        }
        return null;
    }

}

我们可以看到,Service层针对Controller层的调用提供方法,并提供一定的逻辑处理,调用Mapper数据层的方法获取数据。

在这里有一部分的关键代码,但是不多,需要我们了解的有以下几点:

1.@Service

2.@Transactional

3.涉及实体类的方法

4.@Autowired(在前面已经分析过,略)

这几点下面将会一一分析。

@Service注解

使用方法

在service类的声明前注释,如下:

@Service
public class BindService {
    

}

源代码

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
    @AliasFor(
        annotation = Component.class
    )
    String value() default "";
}

分析原理

可以看到,其实现与@Component,@Controller,@Respository等实现类似,

@service @Controller @Respository注解上面都标注了@Component注解,它们之间是等效的

只是为了分层标注,其实现原理均为:向IOC容器中注册beanDefiniton,而背景是自定义标签根据之前讲解的自定义标签解析

解析流程可参考:

@Component解析流程

@Transactional注解

使用方法

@Transactional是spring中声明式事务管理的注解配置方式。

@Transactional注解可以帮助我们把事务开启、提交或者回滚的操作,通过aop的方式进行管理。免去了重复的事务管理逻辑。

示例如下:

 @Transactional
    public Integer bindStuNum(StudentBind studentBind) throws DuplicateKeyException {
        if (UserUtil.getCurrentUserId() != null) {
            studentBind.setUserId(UserUtil.getCurrentUserId());
            if (bindMapper.validateStudentBind(studentBind) > 0) {
                roleMapper.insertRoleUserLink(studentBind.getUserId(), 3);
                UserInfo info = userInfoMapper.selectByUserId(UserUtil.getCurrentUserId());
                info.setStuNum(studentBind.getStuNum());
                info.setRealName(studentBind.getName());
                userInfoMapper.updateUserInfo(info);
                return 1;
            } else {
                return 0;
            }
        }
        return null;
    }

源代码

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.transaction.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Transactional {
    @AliasFor("transactionManager")
    String value() default "";

    @AliasFor("value")
    String transactionManager() default "";

    String[] label() default {};

    Propagation propagation() default Propagation.REQUIRED;

    Isolation isolation() default Isolation.DEFAULT;

    int timeout() default -1;

    String timeoutString() default "";

    boolean readOnly() default false;

    Class<? extends Throwable>[] rollbackFor() default {};

    String[] rollbackForClassName() default {};

    Class<? extends Throwable>[] noRollbackFor() default {};

    String[] noRollbackForClassName() default {};
}

分析原理

首先,对于spring中aop实现原理有了解的话,应该知道想要对一个方法进行代理的话,肯定需要定义切点。

在@Transactional的实现中同样如此,spring为我们定义了以 @Transactional 注解为植入点的切点,这样才能知道@Transactional注解标注的方法需要被代理。
有了切面定义之后,在spring的bean的初始化过程中,就需要对实例化的bean进行代理,并且生成代理对象。
生成代理对象的代理逻辑中,进行方法调用时,需要先获取切面逻辑,@Transactional注解的切面逻辑类似于@Around,在spring中是实现一种类似代理逻辑。

具体代码流程参考:

spring源码阅读--@Transactional实现原理_嘎嘎的博客-优快云博客_@transactional注解实现原理

实体类方法

使用方法

调用实体类的初始化,get和set方法,如下:

 UserInfo info = userInfoMapper.selectByUserId(UserUtil.getCurrentUserId());
                info.setStuNum(studentBind.getStuNum());
                info.setRealName(studentBind.getName());

源代码

package cn.sdu.sdupta.domain;

public class UserInfo {
    private Integer userId;

    private String username;

    private String realName;

    private String headImage;

    private String nickname;

    private String stuNum;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

    public String getHeadImage() {
        return headImage;
    }

    public void setHeadImage(String headImage) {
        this.headImage = headImage;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getStuNum() {
        return stuNum;
    }

    public void setStuNum(String stuNum) {
        this.stuNum = stuNum;
    }
}

分析原理

通过实体类的初始化方法和自定义get,set方法进行数据类的建立和装配,实现数据的封装和对MYBATIS的对接

总结

service层的源码分析到此就结束了

我们发现一些注解和类的底层实现机制的深入了解还是有必要的

对我们提高代码分析能力有一定帮助,同时也加深了个人的代码理解

下一篇分析预计会对mapper层代码进行分析,谢谢阅读

参考资料

@Component,@service,@autowired等注解的实现原理_3075763007的博客-优快云博客_@autowired注解原理
spring源码阅读--@Transactional实现原理_嘎嘎的博客-优快云博客_@transactional注解实现原理
 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值