zoukankan      html  css  js  c++  java
  • Spring学习笔记

    Spring学习笔记02

    一、使用JAVA代码的方式配置Spring

    1.pojo包的同目录下创建一个名为config的包,config包中存放配置类java代码

    package com.hx.config;
    
    import com.hx.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.xml一样
    @Configuration
    @ComponentScan("com.hx.pojo")//扫描到类
    @Import(HxConfig2.class)
    public class HxConfig {
    
        //@Bean:注册一个bean相当于xml文件里面的一个bean标签
        //方法名相当于bean标签中id的属性
        //方法的返回值相当于bean标签中class属性
        @Bean
        public User getUser(){
            return new User();
        }//返回到要注入的bean对象
    }
    

    二、Spirng整合Mybatis

    1.导入依赖

        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.15</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.6</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>5.2.0.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.2.9.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.9.4</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>2.0.2</version>
            </dependency>
        </dependencies>
    

    以上为Spring整合Mybatis时必需的依赖,为了防止IDEA访问不到资源文件还需要加上配置

        <build>
            <resources>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>true</filtering>
                </resource>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>true</filtering>
                </resource>
            </resources>
        </build>
    

    2.编写配置文件spring-dao.xml配置好数据源、sqlSessionFactory以及SqlSessionTemplate

    <?xml version="1.0" encoding="UTF8"?>
    <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"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
    
        <!--DataSource:使用Spring的数据源替换Mybatis的配置-->
        <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/day1118?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=GMT%2B8"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
        </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:com/hx/mapper/*.xml"/>
        </bean>
    
        <!--SqlSessionTemplate就是mybatis中的SqlSession-->
        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
            <!--只能用构造器注入sqlSessionFactory因为其不具有set方法-->
            <constructor-arg index="0" ref="sqlSessionFactory"/>
        </bean>
    
    
        <bean id="userMapper" class="com.hx.mapper.UserMapperImpl">
            <property name="sqlSession" ref="sqlSession"/>
        </bean>
    </beans>
    

    3.编写好接口并在mapper.xml文件中配置好SQL语句

    package com.hx.mapper;
    
    import com.hx.pojo.User;
    
    import java.util.List;
    
    public interface UserMapper {
        public List<User> selectUser();
    }
    
    <?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="com.hx.mapper.UserMapper">
        <select id="selectUser" resultType="user">
            select * from user
        </select>
    </mapper>
    

    4.编写好接口的实现类并注入到Spring中

    package com.hx.mapper;
    
    import com.hx.pojo.User;
    import org.mybatis.spring.SqlSessionTemplate;
    
    import java.util.List;
    
    public class UserMapperImpl implements UserMapper {
    
        //现在所有的操作都使用SqlSessionTemplate来执行了(以前是使用sqlSession)
        private SqlSessionTemplate sqlSession;
    
        public void setSqlSession(SqlSessionTemplate sqlSession){
            this.sqlSession = sqlSession;
        }
        public List<User> selectUser() {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            return mapper.selectUser();
        }
    }
    

    编写一个applicationContext.xml配置文件专门用来注册bean,并将spring-dao.xml配置文件导入

    <?xml version="1.0" encoding="UTF8"?>
    <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"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
    
        <import resource="spring-dao.xml"/>
    
    
        <bean id="userMapper" class="com.hx.mapper.UserMapperImpl">
            <property name="sqlSession" ref="sqlSession"/>
        </bean>
    
    </beans>
    

    5.测试成功之后就可以使用了

    三、声明式事务

    声明式事务是通过AOP实现的,不同于编程式事务的是,只需要在配置文件中配置好声明式事务就可以管理事务,而不用在代码中进行事务的管理了

    1.事务ACID原则:

    事务具有原子性、一致性、隔离性、持久性的特点,在工作中可能会有多个业务操作同一个资源的情况,为了防止数据的损坏或者不一致需要重视事务的管理

    2.声明式事务的配置:见具体代码

    <?xml version="1.0" encoding="UTF8"?>
    <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"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
    
        <!--DataSource:使用Spring的数据源替换Mybatis的配置-->
        <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/day1118?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=GMT%2B8"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
        </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:com/hx/mapper/*.xml"/>
        </bean>
    
        <!--SqlSessionTemplate就是mybatis中的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">
            <property name="dataSource" 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="query" read-only="true"/>
                <tx:method name="*" propagation="REQUIRED"/>
            </tx:attributes>
        </tx:advice>
    
        <!--配置事务切入-->
        <aop:config>
            <aop:pointcut id="txPointCut" expression="execution(* com.hx.mapper.*.*(..))"/>
            <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
        </aop:config>
    
    </beans>
    

    注:该博客只作为自己的学习笔记使用,写的不够详细

    四、总结

    学习过程中遇到的错误

    1.异常com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: 2 字节的 UTF-8 序列的字节 2 无效。

    原因:这个问题的主要原因是xml文件中声明的编码与xml文件本身保存时的编码不一致。
    解决办法:重新设置xml文件保存时的编码与声明的一致

    <?xml version="1.0" encoding="UTF-8"?>
    

    改为

    <?xml version="1.0" encoding="UTF8"?>
    

    2.控制台报错Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.

    原因:这个错误一般是xml文件与实体类的映射错误
    解决办法:仔细查找xml文件中的可能出现错误的地方逐个排查

  • 相关阅读:
    Shiro学习
    【工具】流程图软件
    使用python快速搭建web服务器
    接口并发测试
    什么是REST编程
    Linux下查看cpu使用率
    中文价格识别为数字 java代码
    mysql mvcc 的理解
    Nacos client 客户端cpu占用100% 问题排查和解决方案
    springboot 不停服动态更新定时任务时间(转)
  • 原文地址:https://www.cnblogs.com/huangxuannn/p/15702294.html
Copyright © 2011-2022 走看看