SpringMVC工程之非web部分代码复用,并独立运行

概述

springMVC是位于spring web端的一个框架,是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职责解耦。

下面我们以 https://gitee.com/00fly/java-code-frame/tree/master/springmvc-dbutils 为例来说明:
如何复用此SpringMVC工程的非web部分代码,并脱离web环境使之独立运行。

一、独立运行前提

  1. WebApplicationContext上下文、servletContext上下文配置文件分别定义
  2. 在非web应用程序中定义一个定时任务

二、实现步骤

1. WebApplicationContext上下文配置文件定义

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

	<!-- 使用默认扫描方式, 排除controller类注解 -->
	<context:component-scan base-package="com.fly" use-default-filters="true">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
		<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.RestController" />
		<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />
		<context:exclude-filter type="assignable" expression="com.fly.core.config.SwaggerConfig" />
	</context:component-scan>

	<!-- 配置 读取properties文件 jdbc.properties -->
	<context:property-placeholder location="classpath:jdbc.properties" />

	<!-- 数据库连接池 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
		<!-- 基本属性 url username password driverClassName -->
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="driverClassName" value="${jdbc.driver}" />

		<!--配置初始化大小、最小、最多连接数 -->
		<property name="initialSize" value="1" />
		<property name="maxActive" value="100" />
		<property name="minIdle" value="5" />

		<!--配置获取连接等待超时时间 -->
		<property name="maxWait" value="3000" />

		<!--配置间隔多久进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="6000" />

		<!--配置一个连接在连接池中,最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="30000" />
		<property name="validationQuery" value="SELECT 'x'" />
		<property name="testWhileIdle" value="true" />
		<property name="testOnBorrow" value="false" />
		<property name="testOnReturn" value="false" />

		<!--打开PSCache,并且指定每个连接上的PSCache的大小 -->
		<property name="poolPreparedStatements" value="false" />
		<property name="maxPoolPreparedStatementPerConnectionSize" value="0" />

		<!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 -->
		<property name="filters" value="stat,wall,log4j2" />
	</bean>

	<!-- 事务管理 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	
	<!-- 启用定时任务扫描 -->
	<task:annotation-driven />
	
	<!-- queryRunner注入 -->
	<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
		<constructor-arg ref="dataSource" />
	</bean>

	<!-- 定义jdbcTemplate -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource" />
	</bean>
	
	<!-- 开启aop -->
	<aop:aspectj-autoproxy proxy-target-class="true" />
	
	<!-- 配置 Annotation 驱动,扫描@Transactional注解的类定义事务 -->
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
</beans>

2.servletContext上下文配置文件

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

	<!-- 仅扫描controller类注解,不使用默认扫描方式(默认方式会扫描类上的全部注解) -->
	<context:component-scan base-package="com.fly.**.controller" use-default-filters="false">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
		<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.RestController" />
		<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />
	</context:component-scan>

	<context:component-scan base-package="com.fly.core.config" />

	<!-- 打开 JSR 303 -->
	<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
	<mvc:annotation-driven />
	
	<!-- 开启aop -->
	<aop:aspectj-autoproxy proxy-target-class="true" />

	<!-- 写法1:处理静态文件 -->
	<mvc:default-servlet-handler/>
	
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/views" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

springmvc工程运行结果
在这里插入图片描述
在这里插入图片描述

3. 定义独立运行的类main方法

@Slf4j
public class MainRun
{
    /**
     * Main
     * 
     * @param args
     * @see [类、类#方法、类#成员]
     */
    public static void main(String[] args)
    {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Assert.notNull(context, "context is null");
        log.info("###### Application Started Success ######");
        Arrays.stream(context.getBeanDefinitionNames()).forEach(log::info);
    }
}

4. 开发环境运行main结果

在这里插入图片描述
至此可以看到,main方法代码已经实现了仅加载WebApplicationContext上下文并脱离web环境运行。

5. class文件运行

在项目根目录下执行 mvn clean package会在target文件夹下生成如下文件:
在这里插入图片描述
进入target\classes文件

java -Djava.ext.dirs=../lib com.fly.MainRun

6. jar运行(推荐)

借助maven-shade-plugin插件(推荐)
pom-jar-extract.xml 插件部分配置


			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-shade-plugin</artifactId>
				<version>3.4.0</version>
				<executions>
					<execution>
						<phase>package</phase>
						<goals>
							<goal>shade</goal>
						</goals>
						<configuration>
							<minimizeJar>false</minimizeJar>
							<filters>
								<filter>
									<artifact>*:*</artifact>
								</filter>
							</filters>
							<transformers>
								<!-- 往MANIFEST文件中写入Main-Class是可执行包的必要条件。ManifestResourceTransformer可以轻松实现。 -->
								<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
									<mainClass>com.fly.MainRun</mainClass>
								</transformer>
								<!-- AppendingTransformer 用来处理多个jar包中存在重名的配置文件的合并,尤其是spring -->
								<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
									<resource>META-INF/spring.handlers</resource>
								</transformer>
								<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
									<resource>META-INF/spring.schemas</resource>
								</transformer>
							</transformers>
						</configuration>
					</execution>
				</executions>
			</plugin>
mvn clean package -f pom-jar-extract.xml

进入target执行

java -jar springmvc-dbutils.jar

运行结果
在这里插入图片描述
至此,我们已经实现了SpringMVC工程之非web部分代码复用,并借助插件打成Jar,实现独立运行!

有任何问题和建议,都可以向我提问讨论,大家一起进步,谢谢!

-over-

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值