Spring阶段性学习总结

2020-04-03T00:48:00

学习成果总结

ioc的概念、实现方式

首先:IOC(Inverse of Contro)控制反转,有时候也被称为DI依赖注入,它是一种降低对象耦合关系的一种设计思想。

<beans>
   <bean id = "sale" class = "Sale" singleton = "false">
      <constrctor-arg>
           <ref bean = "tea"/>
      </constrctor-arg>
   </bean>
   <bean id = "tea" class = "Bluetea" singleton = "false"/>
</beans>
class Sale{
    private AbstracTea tea;
    public Sale(AbstracTea tea){
       this.tea = tea;
     }
}

DI依赖注入

全称为Dependency Injection,意思自身对象中的内置对象是通过注入的方式进行创建。

构造器注入

<!--    通过构造方法进行传参-->
    <bean id="phone3" class="com.soft1851.spring.ioc.com.soft1851.spring.mybatis.entity.Phone">
        <constructor-arg value="诺基亚"></constructor-arg>
        <constructor-arg value="1000"></constructor-arg>
    </bean>

setter注入

<!--    通过set方法进行传参-->
    <bean id="phone1" class="com.soft1851.spring.ioc.com.soft1851.spring.mybatis.entity.Phone" p:brand="iPhone11" p:price="6666"/>
    <bean id="phone2" class="com.soft1851.spring.ioc.com.soft1851.spring.mybatis.entity.Phone" p:brand="iPhoneXS" p:price="8888"/>

List、Set、Map等复杂类型的注入

<bean id="student1" class="com.soft1851.spring.ioc.com.soft1851.spring.mybatis.entity.Student">
<property name="id" value="1001"/>
<property name="name" value="Tom"/>
<property name="hobbies">
    <list>
        <value>打游戏</value>
        <value>看电视</value>
        <value>玩手机</value>
    </list>
</property>
    <property name="phone">
        <list>
            <ref bean="phone1" />
            <ref bean="phone2" />
        </list>
    </property>
</bean>
<bean id="student2" class="com.soft1851.spring.ioc.com.soft1851.spring.mybatis.entity.Student">
    <property name="id" value="1002"/>
    <property name="name" value="Tom"/>
    <property name="hobbies">
        <list>
            <value>打游戏</value>
            <value>运动</value>
            <value>编程</value>
        </list>
    </property>
    <property name="phone">
        <list>
            <ref bean="phone1" />
            <ref bean="phone2" />
        </list>
    </property>
</bean>
<bean id="grade" class="com.soft1851.spring.ioc.com.soft1851.spring.mybatis.entity.Grade">
    <property name="name" value="soft1851"></property>
    <property name="students">
        <map>
            <entry key="student1" value-ref="student1"></entry>
            <entry key="student2" value-ref="student2"></entry>
        </map>
    </property>
</bean>

后端工程项目搭建

IDEA项目多模块构建

结构图

搭建过程:

  1. 首先搭建一个主项目,主项目可以不放src
  2. 在主项目上右键,点击new,再点击module
  3. 接下来就进行一个普通项目的搭建过程就可以

maven项目的不同搭建方式

  1. 搭建项目时选择maven
  2. 搭建空项目,在项目上右键,点击add framework,添加maven
  3. 使用父级项目的maven依赖。

子pom文件添加代码块:

<parent>
    <groupId>“父亲级项目组id名”</groupId>
    <artifactId>“父级项目的artifactId”</artifactId>
    <version>“父级项目版本号”</version>
</parent>

父pom文件添加代码块:

<modules>
    <module>“子项目模块名”</module>
</modules>

Spring jdbc Template

xml配置版

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--    <context:annotation-com.soft1851.spring.orm.config/>-->
    <context:component-scan base-package="com.soft1851.spring.orm"/>
    <context:property-placeholder location="db.properties"/>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="initialSize" value="8"/>
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

注解版

配置类代码块

/**
 * @author Johnny
 * @Date: 2020/3/19 08:17
 * @Description:
 */
@Configuration
public class JdbcConfig {
    @Bean
    public static  DruidDataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/bbs?useUnicode=true&characterEncoding=utf8&useSSL=false");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        dataSource.setInitialSize(8);
        return dataSource;
    }

    @Bean
    public static JdbcTemplate jdbcTemplate(DruidDataSource druidDataSource){
        return new JdbcTemplate(druidDataSource);
    }

    @Bean
    public ForumDao forumDao (JdbcTemplate jdbcTemplate){
        return new ForumDaoImpl(jdbcTemplate);
    }


    public static void main(String[] args) {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(JdbcConfig.class);
        ac.scan("com.soft1851.spring.ioc.com.soft1851.spring.orm.config");
        JdbcTemplate jdbcTemplate= (JdbcTemplate)ac.getBean("jdbcTemplate");
        System.out.println(jdbcTemplate);
        ForumDao forumDao = (ForumDao) ac.getBean("forumDao");
        List<Forum> forumList = forumDao.selectAll();
        System.out.println(forumList);
    }

}

SpringMVCxml配置版

web.xml的作用

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <display-name>web</display-name>
    <welcome-file-list>
        <welcome-file>
            index.jsp
        </welcome-file>
    </welcome-file-list>

    <!--    监听器配置:当tomcat启动,加载web.xml配置文件,即web容器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--    上下文初始化:监听到服务器启动,加载applicationContext.xml文件,即spring的容器-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!--    配置解决中文乱码过滤器-->
    <filter>
        <filter-name>encoding-filter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>


    <filter-mapping>
        <filter-name>encoding-filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--    控制器配置:当tomcat启动是,加载springMVC-servlet.xml控制器配置-->
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springMVC-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!--    mvc控制器规则为/-->
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

SpringMVC-servlet.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:mvc="http://www.alibaba.com/schema/stat"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.alibaba.com/schema/stat http://www.alibaba.com/schema/stat.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <!--启动mvc注解驱动-->
    <mvc:annotation-driven/>
<!--    扫描含有注解的包(控制器所在的包)-->
    <context:component-scan base-package="com.soft1851.spring.web.controller"/>
</beans>

controller层常用注解

  • @Controller

@Controller 用于标记在一个类上,使用它标记的类就是一个SpringMVC Controller 对象。分发处理器将会扫描使用了该注解的类的方法,并检测该方法是否使用了@RequestMapping 注解。@Controller 只是定义了一个控制器类,而使用@RequestMapping 注解的方法才是真正处理请求的处理器

  • @RequestMapping

@Controller 用于标记在一个类上,使用它标记的类就是一个SpringMVC Controller 对象。分发处理器将会扫描使用了该注解的类的方法,并检测该方法是否使用了@RequestMapping 注解。@Controller 只是定义了一个控制器类,而使用@RequestMapping 注解的方法才是真正处理请求的处理器

  • @RequestParam

将请求参数绑定到你控制器的方法参数上(是springmvc中接收普通参数的注解)

  • @RequestHeader

使用 @RequestHeader 注解绑定 HttpServletRequest 头信息到Controller 方法参数

  • @ModelAttribute

SpringMVC 支持使用 @ModelAttribute 和 @SessionAttributes 在不同的模型和控制器之间共享数据。 @ModelAttribute 主要有两种使用方式,一种是标注在方法上,一种是标注在 Controller 方法参数上。

当 @ModelAttribute 标记在方法上的时候,该方法将在处理器方法执行之前执行,然后把返回的对象存放在 session 或模型属性中,属性名称可以使用 @ModelAttribute(“attributeName”) 在标记方法的时候指定,若未指定,则使用返回类型的类名称(首字母小写)作为属性名称。

SpringMVC注解版

WebApplicationConfig配置

package com.soft1851.springmvc.web.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * @author Jack
 * @Date: 2020/3/24 10:22
 * @Description:
 */
public class WebApplicationConfig implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        //创建一个基于注解得Web应用上下文配置对象,实现AnnotationConfigRegistry
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        //将WebMvcConfig的配置类注册进来
        ctx.register(WebMvcConfig.class);
        //设置servletContext
        ctx.setServletContext(servletContext);
        //刷新
        ctx.refresh();
        //配置了ctx的映射规则的对象
        ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
        //添加规则
        registration.addMapping("/");
        //设置该servlet的启动优先级
        registration.setLoadOnStartup(1);
    }
}

WebMvcConfig配置

package com.soft1851.springmvc.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.spring5.ISpringTemplateEngine;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;

/**
 * @author Jack
 * @Date: 2020/3/24 10:22
 * @Description:
 */
@Configuration
@ComponentScan("com.soft1851.springmvc.web")
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
    @Bean
    public SpringResourceTemplateResolver  springResourceTemplateResolver(){
        return new SpringResourceTemplateResolver();
    }

    private ITemplateResolver iTemplateResolver(){
        springResourceTemplateResolver().setPrefix("classpath:/templates/");
        springResourceTemplateResolver().setSuffix(".html");
        springResourceTemplateResolver().setTemplateMode(TemplateMode.HTML);
        //解决乱码
        springResourceTemplateResolver().setCharacterEncoding("UTF-8");
        return springResourceTemplateResolver();
    }

    @Bean
    public TemplateEngine templateEngine(){
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setEnableSpringELCompiler(true);
        engine.setTemplateResolver(iTemplateResolver());
        return engine;
    }

    @Bean
    public ViewResolver viewResolver (){
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine((ISpringTemplateEngine) templateEngine());
        resolver.setCharacterEncoding("UTF-8");
        return resolver;
    }
}

各种配置之间的关系和装配

单元测试写法的变化

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringDataSourceConfig.class})
@WebAppConfiguration("src/main/resources")
public class RankDaoTest {
    @Autowired
    private  RankDao rankDao;

    @Test
    public void batchInsert() {
        List<Rank> rankList = new ArrayList<>(){{
            this.add(Rank.builder().title("21313").author("1231231").duration("123123").pic("123123").build());
            this.add(Rank.builder().title("21313").author("1231231").duration("123123").pic("123123").build());
            this.add(Rank.builder().title("21313").author("1231231").duration("123123").pic("123123").build());
        }};
        int row = rankDao.batchInsert(rankList).length;
    }
}

Thymeleaf视图引擎

SpringBoot默认视图引擎

配置方法

基本标签的使用方法

Spring中的注解式事务

事务的概念和作用

注解式事务的开启和配置、使用

HttpClient和JSoup实现爬虫

步骤

注意点

Spring整合Mybatis

xml配置方法

mybatis-config.xml文件代码块

<?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>
    <!--属性-->
    <!--    <properties></properties>-->
    <!--设置-->
    <settings>
        <!--设置启用数据库字段下划线映射到java对象的驼峰式命名属性,默认为false-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
<!--    类型命名-->
        <typeAliases>
            <typeAlias type="com.soft1851.spring.mybatis.entity.Forum" alias="Forum"></typeAlias>
            <typeAlias type="com.soft1851.spring.mybatis.entity.Clazz" alias="Clazz"></typeAlias>
            <typeAlias type="com.soft1851.spring.mybatis.entity.Course" alias="Course"></typeAlias>
            <typeAlias type="com.soft1851.spring.mybatis.entity.CourseStudent" alias="CourseStudent"></typeAlias>
            <typeAlias type="com.soft1851.spring.mybatis.entity.Student" alias="Student"></typeAlias>
            <typeAlias type="com.soft1851.spring.mybatis.entity.Teacher" alias="Teacher"></typeAlias>
        </typeAliases>
    <!--类型处理器-->
    <!--    <typeHandlers></typeHandlers>-->
    <!--对象工厂-->
    <!--    <objectFactory type=""/>-->
    <!--插件-->
    <!--    <plugins>-->
    <!--        <plugin interceptor=""></plugin>-->
    <!--    </plugins>-->
    <!--配置环境-->
    <!--    <environments default="">-->
    <!--环境变量-->
    <!--        <environment id="">-->
    <!--事务管理器-->
    <!--            <transactionManager type=""></transactionManager>-->
    <!--数据源-->
    <!--            <dataSource type="">-->
    <!--            </dataSource>-->
    <!--        </environment>-->
    <!--    </environments>-->
    <!--数据库厂商标识-->
    <!--    <databaseIdProvider type=""/>-->
    <!--映射器-->
    <!--    <mapperss></mappers>-->
</configuration>

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

    <!--读取外部的数据库属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--扫描含有注解的包-->
    <context:component-scan base-package="com.soft1851.spring.mybatis.service.impl"/>
    <!-- 启动上下文的注解配置 -->
    <context:annotation-config/>
    <!-- 启动AOP支持 -->
    <aop:aspectj-autoproxy/>

    <!-- 创建dataSource对象 -->
    <bean id="dataSource"
          class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="initialSize" value="1"/>
        <property name="minIdle" value="1"/>
        <property name="maxActive" value="20"/>
        <property name="maxWait" value="60000"/>
        <property name="timeBetweenEvictionRunsMillis" value="60000"/>
        <property name="minEvictableIdleTimeMillis" value="300000"/>
        <property name="poolPreparedStatements" value="true"/>
    </bean>


    <!-- 在springIOC容器中创建mybatis核心类sqlSessionFactor -->
    <bean id="sqlSessionFactory"
          class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 需要 dataSource -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 引入mybatis配置文件 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--指定实体类所在包-->
        <property name="typeAliasesPackage" value="com.soft1851.spring.mybatis.entity" />
        <!-- 自动扫描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:mappers/*.xml"/>
    </bean>

    <!-- 通过Mapper扫描器MapperScannerConfigurer,批量将 basePackage指定包中的接口全部生成Mapper动态代理对象 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.soft1851.spring.mybatis.mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory">
        </property>
    </bean>

    <!--事务管理器配置 -->
    <bean id="manager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
          p:dataSource-ref="dataSource"/>

    <!-- 使用声明式事务 -->
    <tx:annotation-driven transaction-manager="manager"/>

</beans>

注解方法

Mybatis详解

基本使用

关系映射

动态SQL

当前页面是本站的「Baidu MIP」版。发表评论请点击:完整版 »