编程文汇

spring boot 最小依赖工程, 并使用log4j2

1

有时候, 我们只是想写个单纯spring程序, 并沿用spring boot的习惯, springboot帮我们预先配置了不少设置, 能省不少事. 如果使用正常的方式创建工程, 会发现一个空工程, 会依赖很多包, 这就会增加项目启动时需要的内存, 以及发布时程序的体积.

2

那么如何建立一个最简spring boot项目呢: 关键是build.gradle .
用spring boot starter 新建一个空工程, 用一下内容替换build.gradle, 这里使用jar都是当前的最新版本. 依赖数减少了一半吧.

buildscript {
     ext.springv = '5.1.9.RELEASE'
     ext.springbootv = '2.1.7.RELEASE'
}
plugins {
    id 'org.springframework.boot' version "2.1.7.RELEASE"
	id 'java'
}


group = 'com.ez'
version = '0.0.1'
sourceCompatibility = JavaVersion.VERSION_12
targetCompatibility = JavaVersion.VERSION_12
[compileJava, compileTestJava, javadoc]*.options*.encoding = 'UTF-8'

repositories {
	maven { url 'http://maven.aliyun.com/nexus/content/groups/public' }
	mavenCentral()
}

dependencies {
    // spring boot 帮助启动
    compile group: 'org.springframework.boot', name: 'spring-boot-autoconfigure', version: "${springbootv}" , transitive: false
    compile group: 'org.springframework.boot', name: 'spring-boot', version: "${springbootv}" , transitive: false
    
    // spring bean 核心, 基本缺一不可
    compile group: 'org.springframework', name: 'spring-context', version: "${springv}" , transitive: false
    compile group: 'org.springframework', name: 'spring-core', version: "${springv}" , transitive: false
    compile group: 'org.springframework', name: 'spring-beans', version: "${springv}" , transitive: false
    compile group: 'org.springframework', name: 'spring-aop', version: "${springv}" , transitive: false
    compile group: 'org.springframework', name: 'spring-expression', version: "${springv}" , transitive: false
    
    // log4j
    compile group: 'commons-logging', name: 'commons-logging', version: '1.2'
    compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.12.1'
    compile group: 'org.apache.logging.log4j', name: 'log4j-jcl', version: '2.12.1'
    
    // 可选包
    
    // 单元测试包
    testImplementation group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: "${springbootv}" , transitive: false
    testImplementation group: 'org.springframework.boot', name: 'spring-boot-test', version: "${springbootv}" , transitive: false
    testImplementation group: 'org.springframework', name: 'spring-test', version: "${springv}" , transitive: false
    testImplementation group: 'junit', name: 'junit', version: '4.12' 
    
}

test {
	useJUnitPlatform()
}

运行试试

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class G3Application {
  public static void main(String[] args) throws Exception {
    SpringApplication.run(G3Application.class, args);
  }
}

spring 和 springboot的annotation都可以正常使用.