Spring Boot:字符串占位符

My GitHub Home Page

准确来说,这篇文章与 Spring Boot 无关,只是在 Spring Guides 里经常出现,这里推荐用在你的日常项目中。

String

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;
    }

    public String toString() {
        String format = "Greeting[id=%d, content=%s]";
        return String.format(format, id, content);
    }

}

public static void main(String[] args) {
    Greeting greeting = new Greeting(1, "Hello World!");
    System.out.printf(greeting.toString());
    // Greeting[id=1, content=Hello World!]
}

Logger

package hello;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 Logger logger = LoggerFactory.getLogger(GreetingController.class);

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @GetMapping("/greeting")
    public Greeting greeting(@RequestParam(name = "name", defaultValue = "World") String name) {
        Greeting greeting = new Greeting(counter.incrementAndGet(), String.format(template, name));

        logger.info("Greeting[id={}, content={}]", greeting.getId(), greeting.getContent());
        // brower: http://localhost:8080/greeting
        // Greeting[id=1, content=Hello, World!]

        return greeting;
    }

}