一:步骤
1-:在https://start.spring.io/新建项目,其中,Dependencies选择“Spring Web”;
二:相关命令
./mvnw spring-boot:run 启动项目
三:简单的Spring例子:
package com.time.message;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class MessageApplication {
public static void main(String[] args) {
SpringApplication.run(MessageApplication.class, args);
}
@GetMapping("/hello")
public String hello(@RequestParam(value = "name",defaultValue = "World") String name){
return String.format("Hello %s!",name);
}
}
四:RESTful Web Service
package com.time.message.restservice;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.atomic.AtomicLong;
@RestController
public class GreetingController {
private static final String template = "Hello %s!";
private final AtomicLong counter = new AtomicLong();
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(value = "name",defaultValue = "World") String name){
return new Greeting(counter.incrementAndGet(),String.format(template,name));
}
}
其中需要关注:
@GetMapping("/greeting") GET请求方式
@PostMapping("/greeting") POST请求方式
@RequestMapping("/greeting") GET/POST
@RequestMapping(method=GET) 设置为GET
即为: @RequestMapping(value = "/greeting",method = RequestMethod.GET)
五:Scheduling Tasks
package com.time.message.restservice;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTasks {
private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
log.info("The time is now {}", dateFormat.format(new Date()));
}
}
同时,需要在Application中,添加注解-“EnableScheduling”:
package com.time.message;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class MessageApplication {
public static void main(String[] args) {
SpringApplication.run(MessageApplication.class, args);
}
}
网友评论