Spring 学习

来源:互联网 发布:邮箱服务器软件 编辑:程序博客网 时间:2024/06/01 09:16

创建一个RESTful Web服务

@RestControllerpublic 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));    }}

Spring对于restful接口执行返回值自动转化成JSON字符串(Jackson JSON),不需要自己手动处理.在Spring的配置中加入了MappingJackson2HttpMessageConverter用于对象转化JSON

Spring 4’s new @RestController annotation
@RestController注解声明一个Restful的Controller类.上面的示例中定义了一个接口,支持/greeting 的GET请求,并返回一个JSON字符串

@RequestMapping 注解 /greeting 的请求映射到greeting方法.
想指定特定的请求类型使用@RequestMapping(method=GET)方式

@RequestParam 注解 设置请求参数,上面示例中参数name不是必填,如果请求中带有name参数 则覆盖默认的参数值.

RESTful 服务的controller 和传统的MVC controller一个明显的不同就是 HTTP response body . 传统的controller响应一个View(JSP/FreeMarker等),最终传统到一个HTML.而RESTful 服务的controller是一个JSON格式的响应.

调用restful接口

@SpringBootApplicationpublic class Application implements CommandLineRunner {    private static final Logger log = LoggerFactory.getLogger(Application.class);    public static void main(String args[]) {        SpringApplication.run(Application.class);    }    @Override    public void run(String... strings) throws Exception {        RestTemplate restTemplate = new RestTemplate();        Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);        log.info(quote.toString());    }}

Scheduling Tasks

@Componentpublic class ScheduledTasks {    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");    @Scheduled(fixedRate = 5000)    public void reportCurrentTime() {        System.out.println("The time is now " + dateFormat.format(new Date()));    }}

@Scheduled 注解定义了一个定时任务,上面示例中使用了fixedRate用来指定定时任务的调用间隔.
其他的配置参数

  • fixedDelay=5000
  • fixedRate=5000
  • initialDelay=1000, fixedRate=5000
  • cron="*/5 * * * * MON-FRI" 使用cron 表达式指定定时任务的调用时间

JDBC with Spring

使用Spring的JdbcTemplate

@SpringBootApplicationpublic class Application implements CommandLineRunner {    private static final Logger log = LoggerFactory.getLogger(Application.class);    public static void main(String args[]) {        SpringApplication.run(Application.class, args);    }    @Autowired    JdbcTemplate jdbcTemplate;    @Override    public void run(String... strings) throws Exception {        log.info("Creating tables");        jdbcTemplate.execute("DROP TABLE customers IF EXISTS");        jdbcTemplate.execute("CREATE TABLE customers(" +                "id SERIAL, first_name VARCHAR(255), last_name VARCHAR(255))");        // Split up the array of whole names into an array of first/last names        List<Object[]> splitUpNames = Arrays.asList("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long").stream()                .map(name -> name.split(" "))                .collect(Collectors.toList());        // Use a Java 8 stream to print out each tuple of the list        splitUpNames.forEach(name -> log.info(String.format("Inserting customer record for %s %s", name[0], name[1])));        // Uses JdbcTemplate's batchUpdate operation to bulk load data        jdbcTemplate.batchUpdate("INSERT INTO customers(first_name, last_name) VALUES (?,?)", splitUpNames);        log.info("Querying for customer records where first_name = 'Josh':");        jdbcTemplate.query(                "SELECT id, first_name, last_name FROM customers WHERE first_name = ?", new Object[] { "Josh" },                (rs, rowNum) -> new Customer(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name"))        ).forEach(customer -> log.info(customer.toString()));    }}

Spring的文件上传

使用MultipartFile

@Controllerpublic class FileUploadController {    @RequestMapping(value="/upload", method=RequestMethod.GET)    public @ResponseBody String provideUploadInfo() {        return "You can upload a file by posting to this same URL.";    }    @RequestMapping(value="/upload", method=RequestMethod.POST)    public @ResponseBody String handleFileUpload(@RequestParam("name") String name,            @RequestParam("file") MultipartFile file){        if (!file.isEmpty()) {            try {                byte[] bytes = file.getBytes();                BufferedOutputStream stream =                        new BufferedOutputStream(new FileOutputStream(new File(name)));                stream.write(bytes);                stream.close();                return "You successfully uploaded " + name + "!";            } catch (Exception e) {                return "You failed to upload " + name + " => " + e.getMessage();            }        } else {            return "You failed to upload " + name + " because the file was empty.";        }    }}
0 0
原创粉丝点击