通过spring-context创建可执行jar
程序员文章站
2022-03-07 10:06:06
...
1、新建一个maven工程;
2、pom.xml中引入spring-context dependency
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> </dependencies>
3、添加maven的compiler 和 jar plugin
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <encoding>${project.build.sourceEncoding}</encoding> <source>${java.version}</source> <target>${java.version}</target> <compilerArgs> </compilerArgs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifest> <!-- 指定入口函数 --> <mainClass>com.huatech.core.Bootstrap</mainClass> <!-- 是否添加依赖的jar路径配置 --> <addClasspath>true</addClasspath> <!-- 依赖的jar包存放位置,和生成的jar放在同一级目录下 --> <classpathPrefix>lib</classpathPrefix> </manifest> </archive> </configuration> </plugin> </plugins> </build>
4、启动类添加main方法
package com.huatech.core; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.scheduling.annotation.EnableScheduling; @ComponentScan(basePackages="com.huatech.core") @EnableScheduling public class Bootstrap { @SuppressWarnings("resource") public static void main(String[] args) { System.out.println("starting jar-demo ..."); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Bootstrap.class); // //1. 初始化bean读取器和扫描器 // AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); // //2.注册bean配置类 // context.register(Bootstrap.class); // context.register(ScheduleConfig.class); // //3.刷新上下文 // context.refresh(); // 优雅停机 context.registerShutdownHook(); } }
5、添加一个测试类
package com.huatech.core.service; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class TestSchedule { @Scheduled(fixedDelay = 2000) public void log(){ System.out.println("["+new Date() +"]--"); } }