Spring框架讲解

Spring-MVC.xml:

Spring MVC 中如果配置了 mvc:annotation-driven ,则所有的 Controller 就会被解析,所以相应的 .do 请求就会被 Controller 处理,因此这个配置至关重要。当请求没有匹配到处理类(其中包括没有配置 mvc:annotation-driven 或者 访问的是静态资源文件)时,就会去找 mvc:default-servlet-handler (处理静态资源文件)配置的 DefaultServletHttpRequestHandler 默认处理器处理了

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-4.2.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
                        http://www.springframework.org/schema/aop
                        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
    <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
    <context:component-scan base-package="com.zyy.controller" >
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
    </context:component-scan>
    <mvc:annotation-driven >
      <!--Spring 3.0.x中使用了mvc:annotation-driven后,默认会帮我们注册默认处理请求-->
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                        <value>application/x-www-form-urlencoded;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
</beans>

jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=PRC&useSSL=false
username=root
password=admin
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000

spring-mvc.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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <!-- 自动扫描 -->
    <context:component-scan base-package="com.zyy">
        <context:exclude-filter type="annotation"
                                expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
    <!-- 加载配置文件 -->
    <!-- 引入配置文件 -->
    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 连接池最大数量 -->
        <property name="maxActive" value="${maxActive}" ></property>
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="${maxIdle}" ></property>
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${minIdle}" ></property>
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${maxWait}" ></property>
    </bean>
    <!-- spring和mybatis完美整合,不需要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自动扫描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean>
    <!-- DAO接口所在的包名,spring会自动查找其下的类,!注意这句 value="sqlSessionFactory",不是ref而是value -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
      <!--MapperScannerConfigurer是为了解决MapperFactoryBean繁琐而生的,有了MapperScannerConfigurer
就不需要我们去为每个映射接口去声明一个bean了。大大缩减了开发的效率。-->
        <property name="basePackage" value="com.zyy.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>
</beans>

web.xml

<web-app>元素中编写一个<servlet>元素用于配置一个Servlet,它包含有两个主要的子元素:<servlet-name><servlet-class>,分别用于设置Servlet的名称和Servlet的完整类名。另外一个<servlet-mapping>元素用于映射一个已注册的Servlet的一个对外访问路径,它包含有两个子元素:<servlet-name><url-pattern>,分别用于指定映射到哪个Servlet和Servlet的对外访问路径。

<?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>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>spring-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:*.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

Servlet(Server Applet)是Java Servlet的简称,称为小服务程序或服务连接器,用Java编写的服务器端程序,主要功能在于交互式地浏览和修改数据,生成动态Web内容。这是百度百科上的一段话。说简单点Servlet就是对客户端发送过来的请求进行处理,并且作出相应的响应,其本质就是一个实现了Servlet接口的实现类。

命名空间

xmlns ——是XML NameSpace的缩写,因为XML文件的标签名称都是自定义的,自己写的和其他人定义的标签很有可能会重复命名,而功能却不一样,所以需要加上一个namespace来区分这个xml文件和其他的xml文件,类似于java中的package。

xmlns:xsi ——是指xml文件遵守xml规范,xsi全名:xml schema instance,是指具体用到的schema资源文件里定义的元素所准守的规范。即/spring-beans-2.0.xsd这个文件里定义的元素遵守什么标准。

xsi:schemaLocation——是指,本文档里的xml元素所遵守的规范,schemaLocation 属性用来引用(schema)模式文档,解析器可以在需要的情况下使用这个文档对 XML 实例文档进行校验。它的值(URI)是成对出现的,第一个值表示命名空间,第二个值则表示描述该命名空间的模式文档的具体位置,两个值之间以空格分隔。

Bean标签范围配置

1)当scope的取值为singleton

​ Bean的实例化个数:1个
​ Bean的实例化时机:当Spring核心文件被加载时,实例化配置的Bean实例
​ Bean的生命周期:

  • 对象创建:当应用加载,创建容器时,对象就被创建了
  • 对象运行:只要容器在,对象一直活着
  • 对象销毁:当应用卸载,销毁容器时,对象就被销毁了

2)当scope的取值为prototype

​ Bean的实例化个数:多个
​ Bean的实例化时机:当调用getBean()方法时实例化Bean

  • 对象创建:当使用对象时,创建新的对象实例
  • 对象运行:只要对象在使用中,就一直活着
  • 对象销毁:当对象长时间不用时,被Java的垃圾回收器收了

3).其余的request、session、application、这些个只能在web开发中使用到

4.Bean生命周期配置

  • init-method:指定类中的初始化方法名称
  • destroy-method:指定类中销毁方法名称

解释:

<bean id="hah" class="com.qiu.dao.impl.UserDaoImpl" scope="singleton" init-method="init" destroy-method="destroy"></bean>

不过可能会看不到destroy()方法执行,因为在执行之前对象已经被销毁了,如果需要看到destroy()方法的执行可以手动关闭

例:

package com.qiu.test;

import com.qiu.dao.UserDao;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserTest {
    @Test
    public void test01(){
        ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao = (UserDao)app.getBean("hah");
        System.out.println(userDao);
        app.close();

    }
}
UserDaoImplDone
init running...
com.qiu.dao.impl.UserDaoImpl@1e6d1014
destroy running...

5.Bean实例化三种方式

  • 无参构造方法实例化
  • 工厂静态方法实例化
  • 工厂实例方法实例化
<!--    <bean id="hah" class="com.qiu.dao.impl.UserDaoImpl" scope="singleton" init-method="init" destroy-method="destroy"></bean> :调用实例化对象的构造方法-->
<!--        <bean id="hah" class="com.qiu.factory.StaticFactory" factory-method="getUserDao"></bean> :调用工厂的静态方法-->
       <!-- <bean id = "factory" class="com.qiu.factory.DynamicFactory"></bean>
        <bean id = "hah" factory-bean="factory" factory-method="getUserDao"></bean>:调用工厂的非静态方法-->

Bean的依赖注入的数据类型

​ 上面的操作,都是注入的引用Bean,除了对象的引用可以注入,普通数据类型,集合等都可以在容易中进行注入。

​ 注入数据的三种数据类型

  • 普通数据类型
  • 引用数据类型
  • 集合数据类型
1) 普通注入
public void test01(){

  ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
  UserService userService = (UserService) app.getBean("userService");
  System.out.println(userService);
  userService.save();
}
<bean id="userDao" class="com.qiu.dao.impl.UserDaoImpl">
  <property name="username" value="zhangsan"/>
  <property name="age" value="12"/>
</bean>

<bean id="userService" class="com.qiu.service.impl.UserServiceImpl">
  <constructor-arg name="userDao" ref="userDao"></constructor-arg>
</bean>
3)集合类型注入
public class UserTest {
 @Test
 public void test01(){

     ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
     UserService userService = (UserService) app.getBean("userService");
     userService.save();
 }
}
<bean id="userDao" class="com.qiu.dao.impl.UserDaoImpl">
     <property name="strList">
         <list>
             <value>aaa</value>
             <value>aaa</value>
             <value>aaa</value>
         </list>
     </property>
     <property name="userMap">
         <map>
             <entry key="u1" value-ref="user1"/>
             <entry key="u2" value-ref="user2"/>
         </map>
     </property>
     <property name="properties">
         <props>
             <prop key="p1">ppp1</prop>
             <prop key="p2">ppp2</prop>
             <prop key="p3">ppp3</prop>
         </props>
     </property>
 </bean>

 <bean id="user1" class="com.qiu.domain.User">
     <property name="name" value="tom"></property>
     <property name="addr" value="tianjin"></property>
 </bean>

 <bean id="user2" class="com.qiu.domain.User">
     <property name="name" value="lucky"></property>
     <property name="addr" value="yunnan"></property>
 </bean>

 <bean id="userService" class="com.qiu.service.impl.UserServiceImpl">
     <constructor-arg name="userDao" ref="userDao"></constructor-arg>
 </bean>
[aaa, aaa, aaa]
{u1=User{name='tom', addr='tianjin'}, u2=User{name='lucky', addr='yunnan'}}
{p3=ppp3, p2=ppp2, p1=ppp1}
save running...
posted @ 2021-07-08 15:52  Rugal  阅读(84)  评论(0)    收藏  举报