初识Spring
- 介绍
- 特性
- 构建WebService
- 定时任务
一、介绍
Spring框架为基于JAVA的跨平台的现代企业级应用提供了综合性的编程和配置模型。Spring使企业开发人员不用去关心一些非必要的特定的“调度”环境,团队只需集中精力处理应用层的业务逻辑。以此来提高企业应用开发效率。
二、特性
1、依赖注入
2、面向切面
3、mvc web应用 & RESTful Web Service框架
4、对JDBC,JPA,JMS的基本支持等等
三、Building a RESTful Web Service
build with myEcllipse
目标:
浏览器输入:http://localhost:8080/greeting?name=GKQQQ
返回:{“id”:1,”content”:”Hello, GKQQQ!”}
name属性可选,默认值“world”
创建返回信息实体类:
package hello;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
创建restcontroller接受并处理请求
package hello;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
注意:默认情况下,不标识method为GET或POST,则支持两种请求方式。
可以通过@RequestMapping(method=GET)来限制mapping的请求方式。
通过打jar包的方式运行Application
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
注:此方式不需要编写任何的XML配置文件,是一种100%的纯java语言编写的web应用
测试输出以下信息:
{“id”:4,”content”:”Hello, gkq!”}
四、定时任务
build with myEcllipse
目标:
每5秒打印一次当前时间
使用@schedule注解
创建一个定时任务
package hello;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTasks {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 1000)
public void reportCurrentTime() {
System.out.println("The time is now " + dateFormat.format(new Date()));
}
}
注:schedule注解属性
- fixedRate = 5000 每5秒执行一次定时任务
- fixedDelay = 5000 延迟5秒执行定时任务
- cron = “… …” cron表达式
启动定时任务
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class);
}
}
注:不要忘记打上@EnableScheduling注解
测试输出以下信息:
[… …]
The time is now 23:00:18
The time is now 23:00:19
The time is now 23:00:20
The time is now 23:00:21
The time is now 23:00:22