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

文章目录

  • 概述
    • 一、独立运行前提
    • 二、实现步骤
      • 1. WebApplicationContext上下文配置文件定义
      • 2.servletContext上下文配置文件
      • 3. 定义独立运行的类main方法
      • 4. 开发环境运行main结果
      • 5. class文件运行
      • 6. jar运行(推荐)

概述

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


<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">

	
	<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>

	
	<context:property-placeholder location="classpath:jdbc.properties" />

	
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
		
		<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" />

		
		<property name="poolPreparedStatements" value="false" />
		<property name="maxPoolPreparedStatementPerConnectionSize" value="0" />

		
		<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 />
	
	
	<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
		<constructor-arg ref="dataSource" />
	bean>

	
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource" />
	bean>
	
	
	<aop:aspectj-autoproxy proxy-target-class="true" />
	
	
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
beans>

2.servletContext上下文配置文件

spring-mvc.xml


<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">

	
	<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" />

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

	
	<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工程运行结果
SpringMVC工程之非web部分代码复用,并独立运行_第1张图片
SpringMVC工程之非web部分代码复用,并独立运行_第2张图片

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结果

SpringMVC工程之非web部分代码复用,并独立运行_第3张图片
至此可以看到,此代码至加载WebApplicationContext上下文完全可以脱离web环境运行。

5. class文件运行

在项目根目录下执行 mvn clean package会在target文件夹下生成如下文件:
SpringMVC工程之非web部分代码复用,并独立运行_第4张图片
进入target\classes文件

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

6. jar运行(推荐)

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


			<plugin>
				<groupId>org.apache.maven.pluginsgroupId>
				<artifactId>maven-shade-pluginartifactId>
				<version>3.4.0version>
				<executions>
					<execution>
						<phase>packagephase>
						<goals>
							<goal>shadegoal>
						goals>
						<configuration>
							<minimizeJar>falseminimizeJar>
							<filters>
								<filter>
									<artifact>*:*artifact>
								filter>
							filters>
							<transformers>
								
								<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
									<mainClass>com.fly.MainRunmainClass>
								transformer>
								
								<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
									<resource>META-INF/spring.handlersresource>
								transformer>
								<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
									<resource>META-INF/spring.schemasresource>
								transformer>
							transformers>
						configuration>
					execution>
				executions>
			plugin>
mvn clean package -f pom-jar-extract.xml

进入target执行

java -jar springmvc-dbutils.jar

运行结果
SpringMVC工程之非web部分代码复用,并独立运行_第5张图片
至此,我们已经实现了SpringMVC工程之非web部分代码复用,并借助插件打成Jar,实现独立运行!

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

-over-

你可能感兴趣的:(系统架构,Spring,系统架构)