通过spring-context创建可执行jar

阅读更多

1、新建一个maven工程;

 

 2、pom.xml中引入spring-context dependency

	
		
			org.springframework
			spring-context
			${spring.version}
				
	

 

 3、添加maven的compiler 和 jar plugin


		
			
				org.apache.maven.plugins
				maven-compiler-plugin
				3.1
				
					${project.build.sourceEncoding}
					${java.version}
					${java.version}
					 
                      
				
			
			
			
				org.apache.maven.plugins
				maven-jar-plugin
				
					
						
							
							com.huatech.core.Bootstrap
							
							true
							
							lib
						
					
				
			
			
		
	

 

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() +"]--");
	}
	

}

 

你可能感兴趣的:(java,spring)