spring4倾向于基于注解的配置,强化的注解的功能,对比与spring3还是有很多的区别;spring boot对spring的各个组件功能管理,基于默认配置即可简单构建一个spring4的项目,对于小项目是一个比较好的选择,本篇基于java8 gradle的spring boot 1.3版本整理。
基础的gradle配置:
buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.1.RELEASE") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'idea' apply plugin: 'spring-boot' jar { baseName = 'gs-scheduling-tasks' version = '0.1.0' } repositories { mavenCentral() } sourceCompatibility = 1.8 targetCompatibility = 1.8 dependencies { compile("org.springframework.boot:spring-boot-starter-web") testCompile("org.springframework.boot:spring-boot-starter-test") } task "create-dirs" << { sourceSets*.java.srcDirs*.each { it.mkdirs() } sourceSets*.resources.srcDirs*.each { it.mkdirs() } sourceSets*.webapp.srcDirs*.each { it.mkdirs() } }
建立如下结果目录
Application.java
1 package com.spring4.hello; 2 3 import org.springframework.boot.SpringApplication; 4 import org.springframework.boot.autoconfigure.SpringBootApplication; 5 6 /** 7 * @author ff 8 * @Date 15-12-18. 9 * @Discreption 10 */ 11 @SpringBootApplication 12 public class Application { 13 14 public static void main(String[] args) { 15 SpringApplication.run(Application.class, args); 16 } 17 18 }
这样一个简单的项目便建立好了。
1.数据库模块(jpa)
添加对应的gradle配置
compile("org.springframework.boot:spring-boot-starter-data-jpa") compile("mysql:mysql-connector-java")
spring boot会默认读取根目录下application.properties属性文件,可以将数据库配置放入其中
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useUnicode=true spring.datasource.username=root spring.datasource.password=123456 spring.jpa.show-sql=true #spring.jpa.hibernate.ddl-auto=create
2.计划任务模块
添加配置注解@EnableScheduling即可
package com.spring4.hello.task; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.time.LocalTime; /** * @author ff * @Date 15-12-21. * @Discreption */ @Component public class ScheduledTasks { @Scheduled(fixedRate = 1000) public void sayCurrentTime() { LocalTime now = LocalTime.now(); System.out.println("Current Time="+now); } }