JavaWeb:(练习)十六、Spring学习练习二

JavaWeb:(练习)十六、Spring学习练习二

一、学习目标

​ 初次接触Spring框架,学习了Spring的基础,基本了解了Spring的作用和优缺点。

​ 搭建了第一个Spring项目,导入Spring配置文件,学习并练习了IOC控制反转,并且进行Spring Bean管理,以xml配置方式和注解方式分别实现。并且练习了Spring JDBC。由此完成了spring练习一

JavaWeb:(练习)十五、Spring学习练习一

​ 在练习一的基础上,学习并练习了Spring AOP、Spring事务管理等。以下是在练习一的基础上,所改变的练习代码。

注:关于UserDao改为接口,是因为在学习测试Spring集成MyBatis学习,其中包含错误。

二、dao包

1、BankDao

package com.ffyc.spring1.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository(value = "bankDao")
public class BankDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public void addMoney() {
        jdbcTemplate.update("update bank set bank_money = bank_money + 500 where bank_account = 222");
    }

    public void reduceMoney() {
        jdbcTemplate.update("update bank set bank_money = bank_money - 500 where bank_account = 111");
    }
}

2、StudentDao

package com.ffyc.spring1.dao;

import com.ffyc.spring1.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository(value = "studentDao")
public class StudentDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public void save() {

        /*
        JdbcTemplate 中常用的方法
            execute:无返回值,可执行 ddl,增删改语句
            update:执行新增、修改、删除语句;
            queryForXXX:执行查询相关语句;
         */

        List<Student> students = jdbcTemplate.query("select * from student where student_gender = ?", new RowMapper<Student>() {
            @Override
            public Student mapRow(ResultSet resultSet, int i) throws SQLException {
                Student student = new Student();
                student.setStudentId(resultSet.getInt("student_id"));
                student.setStudentNumber(resultSet.getString("student_number"));
                student.setStudentName(resultSet.getString("student_name"));
                return student;
            }
        }, "男");
        System.out.println(students);
    }
}

3、UserDao

package com.ffyc.spring1.dao;

import com.ffyc.spring1.model.User;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository(value = "userDao")
public interface UserDao {
    /*public void save() {
        System.out.println("执行了UserDao的save");
    }*/

    public List<User> findAllUsers();
}

三、model包

1、Bank

package com.ffyc.spring1.model;

import org.springframework.stereotype.Component;

@Component(value = "bank")
public class Bank {
    private Integer bankId;
    private String bankAccount;
    private Integer bankMoney;

    public Bank() {
    }

    public Bank(Integer bankId, String bankAccount, Integer bankMoney) {
        this.bankId = bankId;
        this.bankAccount = bankAccount;
        this.bankMoney = bankMoney;
    }

    public Integer getBankId() {
        return bankId;
    }

    public void setBankId(Integer bankId) {
        this.bankId = bankId;
    }

    public String getBankAccount() {
        return bankAccount;
    }

    public void setBankAccount(String bankAccount) {
        this.bankAccount = bankAccount;
    }

    public Integer getBankMoney() {
        return bankMoney;
    }

    public void setBankMoney(Integer bankMoney) {
        this.bankMoney = bankMoney;
    }

    @Override
    public String toString() {
        return "Bank{" +
                "bankId=" + bankId +
                ", bankAccount='" + bankAccount + '\'' +
                ", bankMoney=" + bankMoney +
                '}';
    }
}

2、Student

package com.ffyc.spring1.model;

import org.springframework.stereotype.Component;

@Component(value = "student")
public class Student {
    private Integer studentId;
    private String studentNumber;
    private String studentName;

    public Student() {
    }

    public Student(Integer studentId, String studentNumber, String studentName) {
        this.studentId = studentId;
        this.studentNumber = studentNumber;
        this.studentName = studentName;
    }

    public Integer getStudentId() {
        return studentId;
    }

    public void setStudentId(Integer studentId) {
        this.studentId = studentId;
    }

    public String getStudentNumber() {
        return studentNumber;
    }

    public void setStudentNumber(String studentNumber) {
        this.studentNumber = studentNumber;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    @Override
    public String toString() {
        return "Student{" +
                "studentId=" + studentId +
                ", studentNumber='" + studentNumber + '\'' +
                ", studentName='" + studentName + '\'' +
                '}';
    }
}

3、User

package com.ffyc.spring1.model;

import org.springframework.stereotype.Component;

@Component(value = "user")
public class User {

    private Integer userId;
    private String userAccount;
    private String userPassword;

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

    public User(Integer userId, String userAccount, String userPassword) {
        System.out.println("有参");
        this.userId = userId;
        this.userAccount = userAccount;
        this.userPassword = userPassword;
    }

    public Integer getUserId() {
        return userId;
    }

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

    public String getUserAccount() {
        return userAccount;
    }

    public void setUserAccount(String userAccount) {
        this.userAccount = userAccount;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    @Override
    public String toString() {
        return "User{" +
                "userId=" + userId +
                ", userAccount='" + userAccount + '\'' +
                ", userPassword='" + userPassword + '\'' +
                '}';
    }

}

四、service包

1、BankService

package com.ffyc.spring1.service;

import com.ffyc.spring1.dao.BankDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service(value = "bankService")
@Transactional
public class BankService {

    @Autowired
    BankDao bankDao;

    public void transMoney() {
        System.out.println("执行了转账操作!");
        bankDao.reduceMoney();
        bankDao.addMoney();
        System.out.println("转账操作执行完成!");
    }

    public BankService() {
    }

    public BankService(BankDao bankDao) {
        this.bankDao = bankDao;
    }

    public BankDao getBankDao() {
        return bankDao;
    }

    public void setBankDao(BankDao bankDao) {
        this.bankDao = bankDao;
    }
}

2、StudentService

package com.ffyc.spring1.service;

import com.ffyc.spring1.dao.StudentDao;
import com.ffyc.spring1.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.ws.soap.Addressing;

@Service(value = "studentService")
public class StudentService {
    /*@Autowired
    StudentDao studentDao;*/

    /*@Autowired
    @Qualifier(value = "studentDao")
    StudentDao studentDao;*/

    /*@Resource
    StudentDao studentDao;*/

    @Resource(name = "studentDao")
    StudentDao studentDao;

    /*public void save() {
        studentDao.save();
    }*/

    public void save() {
        System.out.println("StudentService.save()");
        System.out.println(10/0);
    }

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

3、UserService

package com.ffyc.spring1.service;

import com.ffyc.spring1.dao.UserDao;
import com.ffyc.spring1.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(value = "userService")
@Transactional
public class UserService {
    @Autowired
    UserDao userDao;

/*    public void save() {
        System.out.println("执行了UserService的save");
        userDao.save();
    }*/

    public List<User> findAllUsers() {
        List<User> users = userDao.findAllUsers();
        return users;
    }

    public UserService() {
    }

    public UserService(UserDao userDao) {
        this.userDao = userDao;
    }

    public UserDao getUserDao() {
        return userDao;
    }

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

五、Util工具包

MyBatis

package com.ffyc.spring1.util;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class MyUtil {

    @Before("execution(* com.ffyc.spring1.service.StudentService.save(..))")
    public void saveLog() {
        System.out.println("日志");
    }

    @After("execution(* com.ffyc.spring1.service.StudentService.save(..))")
    public void commit() {
        System.out.println("提交");
    }

    @Around("execution(* com.ffyc.spring1.service.StudentService.delete())")
    public void around(ProceedingJoinPoint proceedingJoinPoint) {
        System.out.println("=======前=======");
        try {
            proceedingJoinPoint.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        System.out.println("=======后=======");
    }

    @AfterThrowing(value = "execution(* com.ffyc.spring1.service.StudentService.save())", throwing = "e")
    public void execption(Throwable e) {
        System.out.println("异常通知:" + e.getMessage());
    }

}

六、配置文件

1、pom.xml


2、config.properties

dirverClassName=com.mysql.cj.jdbc.Driver
url = jdbc:mysql://127.0.0.1:3306/ffycdb?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
uname = root
password = root

3、spring_backups1.xml(备份的一份spring配置文件)

<?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"
       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/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
        <!-- 配置spring要管理的标签 -->
        <!--
            id 生成的对象名
            class 全类名
            name 对象别名,可以为多个
            scope:
                singleton(默认值):在 Spring 中只存在一个 bean 实例, 单例模式.
                prototype:原型 getBean()的时候都会 new Bean()
                request:每次 http 请求都会创建一个 bean, 仅用于 WebApplicationContext 环境
                session:同一个 http session 共享一个 Bean, 不同 Session 使用不同的 Bean, 使用环境同上
         -->
        <!--<bean id="user" class="com.ffyc.spring1.model.User"></bean>-->

        <!-- set方法注入 -->
        <bean id="user" class="com.ffyc.spring1.model.User">
            <property name="userId" value="1"></property>
            <property name="userAccount" value="11"></property>
            <property name="userPassword" value="111"></property>
        </bean>

        <!-- 构造方法注入 -->
        <!--<bean id="user" class="com.ffyc.spring1.model.User">
            <constructor-arg name="userId" value="2"></constructor-arg>
            <constructor-arg name="userAccount" value="22"></constructor-arg>
            <constructor-arg name="userPassword" value="222"></constructor-arg>
        </bean>-->

        <!-- 生成UserDao对象 -->
        <bean id="userdao" class="com.ffyc.spring1.dao.UserDao"></bean>
        <!-- 生成UserService对象,同事注入userDao -->
        <bean id="userservice" class="com.ffyc.spring1.service.UserService">
            <property name="userDao" ref="userdao"></property>
        </bean>

        <context:component-scan base-package="com.ffyc.spring1"></context:component-scan>

</beans>

4、spring_backups2.xml(备份的一份spring配置文件)

<?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <context:component-scan base-package="com.ffyc.spring1"></context:component-scan>

    <!--  导入另一个配置文件  -->
    <import resource="db.xml"></import>

    <!--  基于xml方式  -->
    <!--  配置装有通知的类,将此类交给spring管理  -->
    <bean id="myutil" class="com.ffyc.spring1.util.MyUtil"></bean>

    <!--  编织/织入  -->
    <aop:config>
        <!--  配置切入点  -->
        <aop:pointcut id="save" expression="execution(* com.ffyc.spring1.service.StudentService.save(..))"/>
        <aop:pointcut id="delete" expression="execution(* com.ffyc.spring1.service.StudentService.delete(..))"/>
        <!--  为切入点配置通知  -->
        <aop:aspect ref="myutil">
            <!--  前置通知  -->
            <aop:before method="saveLog" pointcut-ref="save"></aop:before>
            <!--  后置通知  -->
            <aop:after method="commit" pointcut-ref="save"></aop:after>
            <!--  环绕通知  -->
            <aop:around method="around" pointcut-ref="delete"></aop:around>
            <!--  异常通知  -->
            <aop:after-throwing method="execption" throwing="e" pointcut-ref="save"></aop:after-throwing>
        </aop:aspect>
    </aop:config>

</beans>

5、spring.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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.ffyc.spring1"></context:component-scan>

    <!--  导入另一个配置文件  -->
    <import resource="db.xml"></import>

    <!--  基于注解方式  -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

    <!-- 配置 spring 事务管理类, 并注入数据源 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 开启注解事务管理 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

七、demo测试包

1、Demo1

package com.ffyc.spring1.demo.day2;

import com.ffyc.spring1.service.StudentService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Demo2_1 {
    public static void main(String[] args) {
        ApplicationContext app = new ClassPathXmlApplicationContext("spring.xml");
        StudentService studentService = app.getBean("studentService", StudentService.class);

        studentService.save();

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

        studentService.delete();
    }
}

2、Demo2

package com.ffyc.spring1.demo.day2;

import com.ffyc.spring1.service.BankService;
import com.ffyc.spring1.service.StudentService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Demo2_2 {
    public static void main(String[] args) {
        ApplicationContext app = new ClassPathXmlApplicationContext("spring.xml");
        BankService bankService = app.getBean("bankService", BankService.class);

        bankService.transMoney();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值