代碼地址:JillWen_SpringBootDemojavascript
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <!--這裏若是不寫版本會自動繼承spring-boot-starter-parent裏的版本號--> <version>${mysql.version}</version> </dependency>
<plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>${mybatis-generator.version}</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin>
添加一個「Run運行」選項,使用maven運行mybatis-generator-maven-plugin插件, 在 「Command line」 選項中輸入「mybatis-generator:generate -e」html
<plugin> <artifactId>maven-resources-plugin</artifactId> <version>2.5</version> <executions> <execution> <id>copy-xmls</id> <phase>process-sources</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>${basedir}/target/classes</outputDirectory> <resources> <resource> <directory>${basedir}/src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </configuration> </execution> </executions> </plugin>
(參考:http://websystique.com/spring-boot/spring-boot-rest-api-example/):java
@Autowired IUserService userService; /** * 查詢全部用戶 * @return */ @RequestMapping(value = "/", method = RequestMethod.GET) public List<User> listAllUsers() { List<User> users = userService.findAllUsers(); return users; } /** * 根據id查詢用戶 * @param id * @return */ @RequestMapping(value = "/{id}", method = RequestMethod.GET) public User getUser(@PathVariable("id") int id) { logger.info("Fetching User with id {}", id); User user = userService.findById(id); if (user == null) { logger.error("User with id {} not found.", id); } return user; } /** * 新建一個用戶 * @param user * @return */ @RequestMapping(value = "/", method = RequestMethod.POST) public String createUser(@ModelAttribute User user) { //除了@ModelAttribute綁定參數以外,還能夠經過@RequestParam從頁面中傳遞參數/RequestBody ? logger.info("Creating User : {}", user); User exitUser = new User(); exitUser.setId(user.getId()); if (userService.isUserExist(exitUser)) { logger.error("Unable to create. A User with id {} already exist", exitUser.getId()); } userService.saveUser(user); return "success"; } /** * 根據id更新用戶信息 * @param id * @param user * @return */ @RequestMapping(value = "/{id}", method = RequestMethod.PUT) public String updateUser(@PathVariable("id") int id, @ModelAttribute User user) { //RequestBody logger.info("Updating User with id {}", id); User currentUser = userService.findById(id); if (currentUser == null) { logger.error("Unable to update. User with id {} not found.", id); return "fail"; } currentUser.setName(user.getName()); currentUser.setAge(user.getAge()); userService.updateUser(currentUser); return "success"; } /** * 根據id刪除用戶 * @param id * @return */ @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public String deleteUser(@PathVariable("id") int id) { logger.info("Fetching & Deleting User with id {}", id); User user = userService.findById(id); if (user == null) { logger.error("Unable to delete. User with id {} not found.", id); return "fail"; } userService.deleteUserById(id); return "success"; } /** * 刪除全部用戶 * @return */ @RequestMapping(value = "/", method = RequestMethod.DELETE) public String deleteAllUsers() { logger.info("Deleting All Users"); userService.deleteAllUsers(); return "success"; }
測試(使用postman):mysql
查詢全部用戶
查詢id爲1的用戶
建立一個用戶git
更新id爲1的用戶github
(參考http://blog.didispace.com/springbootswagger2/)web
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.2.2</version> </dependency>
@Configuration @EnableSwagger2 public class Swagger2 { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo.server.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot中使用Swagger2構建RESTful APIs") .description("使用Swagger2構建RESTful APIs") .termsOfServiceUrl("http://www.wjcoding.cn/") .contact("Jill") .version("1.0") .build(); } }
@ApiOperation(value="建立用戶", notes="根據User對象建立用戶") @ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User") @RequestMapping(value = "/", method = RequestMethod.POST) public String createUser(@ModelAttribute User user) { //代碼略 }
(參考博客:http://412887952-qq-com.iteye.com/blog/2312274)spring
建立messages.properties(messages_zh_CN.properties,messages_en_US.properties)文件 thymeleaf裏使用#{key}顯示,例如:<p th:text="#{welcome}"></p>sql
#指定message的basename,多個以逗號分隔,若是不加包名的話,默認從classpath路徑開始,默認: messages spring.messages.basename=i18n/messages #設定加載的資源文件緩存失效時間,-1的話爲永不過時,默認爲-1 spring.messages.cache-seconds=3600 #設定Message bundles的編碼,默認: UTF-8 #spring.messages.encoding=UTF-8api
驗證:火狐地址欄裏輸入about:config回車,搜索accept_languages,改爲en_US,en
Locale locale = LocaleContextHolder.getLocale();
(或者Locale locale = RequestContextUtils.getLocale(request);)
String msg = messageSource.getMessage("welcome", null,locale);
區域解析器 默認:AcceptHeaderLocaleResolver 根據HTTP請求的頭部信息accept-language來解析區域
會話區域解析器:SessionLocaleResolver
@Bean public LocaleResolver localeResolver() { SessionLocaleResolver slr = new SessionLocaleResolver(); //設置默認區域 slr.setDefaultLocale(Locale.CHINA); return slr; }
request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, new Locale("en", "US"))
@Bean public LocaleResolver localeResolver() { CookieLocaleResolver slr = new CookieLocaleResolver(); //設置默認區域 slr.setDefaultLocale(Locale.CHINA); slr.setCookieMaxAge(3600);//設置cookie有效期. returnslr; }
@Bean public LocaleResolver localeResolver() { FixedLocaleResolver slr = new FixedLocaleResolver (); //設置默認區域 slr.setDefaultLocale(Locale.US); returnslr; }
@Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor lci = new LocaleChangeInterceptor(); // 設置請求地址的參數,默認爲:locale // lci.setParamName(LocaleChangeInterceptor.DEFAULT_PARAM_NAME); return lci; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); }
注意這個是能夠和會話區域解析器以及Cookie區域解析器一塊兒使用的, 可是不能和FixedLocaleResolver一塊兒使用,不然會拋出異常信息。
驗證:
(參考:http://blog.didispace.com/springbootaoplog/)
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
實現AOP的切面主要有如下幾個要素:
@Aspect @Component @Order(1) public class WebLogAspect { private Logger logger = Logger.getLogger(WebLogAspect.class); ThreadLocal<Long> startTime = new ThreadLocal<>(); @Pointcut("execution(public * com.example.demo.server.controller..*.*(..))") public void webLog(){} @Before("webLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { startTime.set(System.currentTimeMillis()); // 接收到請求,記錄請求內容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 記錄下請求內容 logger.info("URL : " + request.getRequestURL().toString()); logger.info("HTTP_METHOD : " + request.getMethod()); logger.info("IP : " + request.getRemoteAddr()); logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs())); } @AfterReturning(returning = "ret",pointcut = "webLog()") public void doAfterReturning(Object ret) throws Throwable { // 處理完請求,返回內容 logger.info("RESPONSE : " + ret); logger.info("RESPONSE : " + ret); logger.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get())); } }
結果:

(參考http://www.jianshu.com/p/a9b1e2f7a749)
//這裏不能用@NotBlank,由於id類型爲int private int id; //使用groups屬性來給分組命名,而後在須要的地方指定命令便可 @NotBlank(groups=NAME.class) private String name; @Min(1) private Integer age;
@RestController public class ValidateController { @RequestMapping(value="testUser") public void testStudent(@Validated User user) { } @RequestMapping(value="testUser1") public void testStudent1(@Validated(User.NAME.class) User user) { } }
使用 @ScriptAssert 註解校驗複雜的業務邏輯: 若是須要校驗的業務邏輯比較複雜,能夠使用@ScriptAssert來指定進行校驗的方法, 經過方法來進行復雜業務邏輯的校驗,而後返回 true或false來代表是否校驗成功。
@ScriptAssert(lang="javascript",script="com.learn.validate.domain .Student.checkParams(_this.name,_this.age,_this.classes)", groups=CHECK.class) public class Student { //其餘代碼 /注意進行校驗的方法要寫成靜態方法,不然會出現 //TypeError: xxx is not a function 的錯誤 public static boolean checkParams(String name,int age,String classes) { if(name!=null&&age>8&classes!=null) { return true; } else { return false; } } }
在Hibernate Validator(org.hibernate.validator.constraints)中:
@NotEmpty://CharSequence, Collection, Map 和 Array 對象不能是 null 而且相關對象的 size 大於 0。 @NotBlank://String 不是 null 且去除兩端空白字符後的長度(trimmed length)大於 0。
驗證: