Spring mvc(2)spring mvc+quarz+mybatis+druid

来源:互联网 发布:ddg1000驱逐舰数据 编辑:程序博客网 时间:2024/05/17 03:24

1.定时器

pom.xml

<dependency>    <groupId>org.quartz-scheduler</groupId>    <artifactId>quartz</artifactId>    <version>2.2.3</version></dependency>

修改demo-servlet.xml的配置

1.增加     xmlns:task="http://www.springframework.org/schema/task"2.xsi:schemaLocation增加     http://www.springframework.org/schema/task     http://www.springframework.org/schema/task/spring-task-3.2.xsd<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:util="http://www.springframework.org/schema/util"     xmlns:mvc="http://www.springframework.org/schema/mvc"    xmlns:task="http://www.springframework.org/schema/task"    xsi:schemaLocation="http://www.springframework.org/schema/beans       http://www.springframework.org/schema/beans/spring-beans-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/util        http://www.springframework.org/schema/util/spring-util-3.0.xsd        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc.xsd       http://www.springframework.org/schema/task       http://www.springframework.org/schema/task/spring-task-3.2.xsd">    <!-- 定时器相关 -->    <task:annotation-driven />    <!-- 开启注解模式驱动 -->    <mvc:annotation-driven />

Java代码

跟在spring boot里的用法一样

@Component@EnableSchedulingpublic class TimeSchedule {    private static long timeBefore =  System.currentTimeMillis();    @Scheduled(cron = "0/3 * * * * ?")    public void heartBeats() {    }    @Scheduled(cron = "* * * * * ?")    public void sameDay(){        long timeNow = System.currentTimeMillis();        LogCore.BASE.info("heart beats {}",System.currentTimeMillis());        if(!isSameDay(timeBefore, timeNow)){            timeBefore = timeNow;            String statsTimeStr = formatTime(System.currentTimeMillis(),"yyyyMMdd");            LogCore.BASE.info("new day schedule {}",statsTimeStr);        }    }}

2.mybatis+druid

1 pom.xml引入的依赖

        <dependency>            <groupId>org.mybatis</groupId>            <artifactId>mybatis</artifactId>            <version>3.4.4</version>        </dependency>        <dependency>            <groupId>org.mybatis</groupId>            <artifactId>mybatis-spring</artifactId>            <version>1.3.1</version>        </dependency>        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-jdbc</artifactId>        </dependency>        <dependency>            <groupId>com.alibaba</groupId>            <artifactId>druid</artifactId>        </dependency>

2 demo-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:p="http://www.springframework.org/schema/p"     xmlns:context="http://www.springframework.org/schema/context"    xmlns:util="http://www.springframework.org/schema/util"     xmlns:mvc="http://www.springframework.org/schema/mvc"    xmlns:task="http://www.springframework.org/schema/task"    xsi:schemaLocation="http://www.springframework.org/schema/beans       http://www.springframework.org/schema/beans/spring-beans-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/util        http://www.springframework.org/schema/util/spring-util-3.0.xsd        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc.xsd       http://www.springframework.org/schema/task       http://www.springframework.org/schema/task/spring-task-3.2.xsd">    <!-- 定时器相关 -->    <task:annotation-driven />    <!-- 开启注解模式驱动 -->    <mvc:annotation-driven />    <import resource="spring-dao.xml" />    <!-- 扫包 -->    <context:component-scan base-package="demo" />    <context:component-scan base-package="com.alibaba" />    <!-- 静态资源过滤 -->    <mvc:resources location="/resources/" mapping="/resources/**" />    <!-- 视图渲染 jsp/freemaker/velocity -->    <bean        class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <!-- 制定页面存放的路径 -->        <property name="prefix" value="/WEB-INF/pages" />        <!-- 文件的后缀 -->        <property name="suffix" value=".jsp" />    </bean></beans>

3 demo-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:p="http://www.springframework.org/schema/p"     xmlns:context="http://www.springframework.org/schema/context"    xmlns:util="http://www.springframework.org/schema/util"     xmlns:mvc="http://www.springframework.org/schema/mvc"    xmlns:task="http://www.springframework.org/schema/task"    xsi:schemaLocation="http://www.springframework.org/schema/beans       http://www.springframework.org/schema/beans/spring-beans-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/util        http://www.springframework.org/schema/util/spring-util-3.0.xsd        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc.xsd       http://www.springframework.org/schema/task       http://www.springframework.org/schema/task/spring-task-3.2.xsd">    <!-- 定时器相关 -->    <task:annotation-driven />    <!-- 开启注解模式驱动 -->    <mvc:annotation-driven />    <import resource="spring-dao.xml" />    <!-- 扫包 -->    <context:component-scan base-package="demo" />    <!-- 静态资源过滤 -->    <mvc:resources location="/resources/" mapping="/resources/**" />    <!-- 视图渲染 jsp/freemaker/velocity -->    <bean        class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <!-- 制定页面存放的路径 -->        <property name="prefix" value="/WEB-INF/pages" />        <!-- 文件的后缀 -->        <property name="suffix" value=".jsp" />    </bean></beans>

4 增加spring-dao.xml如下

注意在最开始增加了xmlns:p=”http://www.springframework.org/schema/p”以便可以使用p:来方便配置

<?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:mybatis="http://mybatis.org/schema/mybatis-spring"    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd       http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">    <!-- 该包下的类支持注解,表示会被当作{@code mybatis mapper}处理 配置了之后表示可以自动引入mapper类 -->    <mybatis:scan base-package="demo" />    <!--引入属性文件 -->    <context:property-placeholder location="classpath:configuration.properties" />    <!--数据库连接 -->    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"        init-method="init" destroy-method="close">        <property name="url" value="${jdbc.url}" />        <property name="username" value="${jdbc.username}" />        <property name="password" value="${jdbc.password}" />        <!-- 配置初始化大小、最小、最大 -->        <property name="initialSize">            <value>1</value>        </property>        <property name="maxActive">            <value>5</value>        </property>        <property name="minIdle">            <value>1</value>        </property>        <!-- 配置获取连接等待超时的时间 -->        <property name="maxWait">            <value>60000</value>        </property>        <!-- 配置监控统计拦截的filters -->        <property name="filters">            <value>stat</value>        </property>        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->        <property name="timeBetweenEvictionRunsMillis">            <value>60000</value>        </property>        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->        <property name="minEvictableIdleTimeMillis">            <value>300000</value>        </property>        <!-- <property name="validationQuery"><value>SELECT 'x'</value></property>             <property name="testWhileIdle"><value>true</value></property> <property name="testOnBorrow"><value>false</value></property>             <property name="testOnReturn"><value>false</value></property> <property name="poolPreparedStatements"><value>true</value></property>             <property name="maxOpenPreparedStatements"><value>20</value></property> -->    </bean>    <!-- mybatis配置 -->    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"        p:dataSource-ref="dataSource"         p:mapperLocations="classpath*:mapper/**/*.xml" /></beans>   

5 增加web.xml配置下druid的监控

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" ><web-app>    <display-name>Archetype Created Web Application demo_mvc</display-name>    <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>classpath:applicationContext.xml</param-value>    </context-param>    <filter>        <filter-name>encoding</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>    </filter>    <filter-mapping>        <filter-name>encoding</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>    <listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>    <listener>        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>    </listener>     <!-- druid web 监控 -->      <servlet>          <servlet-name>DruidStatView</servlet-name>          <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>      </servlet>      <!-- servlet start -->    <servlet>        <servlet-name>demo</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <init-param>            <param-name>contextConfigLocation</param-name>            <param-value>classpath:demo-servlet.xml</param-value>        </init-param>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>          <servlet-name>DruidStatView</servlet-name>          <url-pattern>/druid/*</url-pattern>      </servlet-mapping>      <servlet-mapping>        <servlet-name>demo</servlet-name>        <url-pattern>/</url-pattern>    </servlet-mapping>    <!-- end --></web-app>

6 写dao和mapper

dao:

package demo.dao;import org.apache.ibatis.annotations.Param;import org.springframework.stereotype.Repository;@Repositorypublic interface DemoDao {    Integer count();    Integer countColumsByTableName(@Param("tableName") String tableName);}

demo-mvc/src/main/resources/mapper/DemoMapper.xml:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="demo.dao.DemoDao">    <select id="count" resultType="Integer" parameterType="java.lang.String">        select        count(1) from t_user    </select>    <select id="countColumsByTableName" resultType="Integer"        parameterType="java.lang.String" statementType="STATEMENT">        <![CDATA[select count(1) from ${tableName}]]>    </select></mapper>

7 mybatis参数和返回值

  • 传入id返回map:
@MapKey("uid")     public Map<Long, User> getUsersByIds(List<Long> uids);
<resultMap id="UserResultMap" type="demo.User" >    <result column="UID" property="uid"/>    <result column="name" property="name"/></resultMap><select id="getUsersByIds" resultMap="UserResultMap" parameterType="java.lang.Long">SELECT * FROM t_user    WHERE        uid IN         <foreach collection="list" item="uid" open="(" close=")" separator=",">            #{uid}        </foreach>   ) </select>
  • 传入map,返回一个对象
UserDesc queryUserDesc(Map<String, Object> queryParams);
<select id="queryUserDesc" resultMap="UserDescResultMap"        parameterType="Map">        select * from t_user        where 1=1        <if test="uid != null and uid != ''">            and uid = #{uid}        </if>    </select></mapper>
  • 返回一个List
    只要将上一步的返回值改为
List<UserDesc>就行

最后,如何检查druid是否正常工作

1.打开druid的页面

这里写图片描述
能看到这儿说明web.xml配置的druid servlet生效
但是查看下数据源为空
在控制台启动jvisualvm
这里写图片描述
搜索druid.DataSource是否有这个对象实例
如果没有往往是 spring-dao.xml配置文件没有被spring扫描
这里我们在demo-servlet配置了

<import resource="spring-dao.xml" />

所以可以引入
还有种方式在web.xml配置

    <context-param>          <param-name>contextConfigLocation</param-name>          <param-value>/WEB-INF/config/spring-*.xml</param-value>      </context-param>  

也是可以的,可以根据自己的习惯来选择

原创粉丝点击