1. 程式人生 > >spring boot入門練習小結

spring boot入門練習小結

小案例:(期間遇到的bug在程式碼相應位置都有註釋)

專案結構


pom.xml

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.imooc</groupId>
	<artifactId>girl</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>girl</name>
	<description>Demo project for Spring Boot</description>

	<!-- 父工程裡描述了相關的依賴及版本號 -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.4.1.RELEASE</version>
		<relativePath/>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

    </dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

整個工程的啟動類:

/**
 * --------要放在Controller的上一層,不然not mapping -----------
 * Hello world!
 * 啟動整個應用
 */
@SpringBootApplication
public class App 
{
    public static void main( String[] args )
    {
        SpringApplication.run(App.class, args);
    }
}
AnimalController.java
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.oliver.springbootpra.entity.Animal;
import com.oliver.springbootpra.repository.AnimalRepository;

@RestController
@RequestMapping("/animal")
public class AnimalController {
	//注入持久化類,利用JPA
        //定義持久化介面AnimalRepository extends JpaRepository<Animal, Integer>
@Autowired private AnimalRepository animalRepository; //獲取全部動物 @GetMapping("/getAll") public List<Animal> getAll(){ return animalRepository.findAll(); } //新增 @PostMapping("/add") public Animal add(@RequestParam("name") String name,@RequestParam("color") String color){ System.out.println(name+"------"+color); Animal animal = new Animal(); animal.setName(name); animal.setColor(color); return animalRepository.save(animal); } /** * 帶驗證的新增 * 1. 在實體類中新增驗證資訊 * 2. 在Controller的method中新增:@Valid ,BindingResult * @param animal * @param bindingResult 記錄了@Valid下不通過時的所有錯誤message * @return */
@PostMapping("/addWithValid") public Object addWithValid(@Valid Animal animal,BindingResult bindingResult){ if(bindingResult.hasErrors()){ return bindingResult.getFieldError().getDefaultMessage(); } return animalRepository.save(animal); } //刪除 @DeleteMapping("/delete/{id}") public void delete(@PathVariable("id") Integer id){ animalRepository.delete(id); } //修改 @PutMapping("/put/{id}") public void put(@PathVariable("id") Integer id,@RequestParam("name") String name,@RequestParam("color") String color){ Animal animal = new Animal(); animal.setId(id); animal.setName(name); animal.setColor(color); animalRepository.save(animal); } //根據id查詢 @GetMapping("/get/{id}") public Animal getById(@PathVariable("id") Integer id){ return animalRepository.findOne(id); } //根據color查詢,spring boot沒有幫我們實現,我們要自己擴充套件animalRepository的方法,若根據xx查詢,方法名要符合 findByXX @GetMapping("/get/color/{color}") public List<Animal> getByColor(@PathVariable("color")String color){ return animalRepository.findByColor(color); } }
Animal.java
@Entity
public class Animal {
	
	@Id
	@GeneratedValue
	private Integer id;
	
	@NotEmpty(message="名字不能為空")
	private String name;
	
	private String color;
AnimalRepository.java
// animal的持久化介面
public interface AnimalRepository extends JpaRepository<Animal, Integer>{ //泛型:第一個是實體類,第二個是主鍵的型別
	//  擴充套件方法:根據color查詢
	//---方法名要符合 findByXX---
	List<Animal> findByColor(String color);
}

配置檔案:

application.yml
spring:
  profiles:
# 多環境配置
     active: dev
#    active: prod  上線時使用的配置
# 強制使用預設編碼(UTF-8)
  http:
    encoding:
      force: true
# 公共配置
# 配置資料庫
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1/pra?useUnicode=true&characterEncoding=utf-8
    username: root
    password: root
# 配置jpa
  jpa:
      hibernate:
       ddl-auto: update # 可選值: update,create,create-drop,none,validate
      show-sql: true # 注意縮排,錯了不會報錯,也沒效果
Application-dev.xml
server:
  port: 8083 # 修改內建埠號
Application-prod.xml
server:
  port: 8083 # 修改內建埠號



切面:

package com.oliver.springbootpra.aspect;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
 * aop
 * 1. 現在pom中引入spring-boot-starter-aop的依賴
 * 2. 如下,新建一個類,@Aspect,@Before...
 * @author oliver
 */
@Aspect
@Component
public class HttpAspect {
	//獲取日誌輸出物件
	private static final Logger logger = LoggerFactory.getLogger(HttpAspect.class);
	
	@Pointcut("execution(* com.oliver.springbootpra.controller.*.*(..))")
	public void pointCut(){
		
	}
	
	/**
	 * 業務方法執行前
	 * @param joinPoint 用來獲取請求的類名,方法名,引數
	 */
	@Before("pointCut()")
	public void beforeExec(JoinPoint joinPoint){
		System.out.println("beforeExec..");
		
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		
		//url
		logger.info("url={}",request.getRequestURL());
		//method
		logger.info("method={}",request.getMethod());
		//ip
		logger.info("ip={}",request.getRemoteAddr());
		//類方法
		logger.info("類名.方法名"+joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
		//引數
		logger.info("引數"+joinPoint.getArgs());
	}
	
	/**
	 * 業務方法執行後
	 */
	@After("pointCut()")
	public void afterExec(){
		System.out.println("afterExec..");
	}
	
	/**
	 * 
	 * @param object 業務方法執行後返回的結果
	 */
	@AfterReturning(returning="object",pointcut="pointCut()")
	public void doAfterReturning(Object object){
		logger.info("args={}",object.toString());
	}
}


補充:

問題1:本來專案可以執行,但在新增parent節點後啟動失敗

No active profile set, falling back to default profiles: default
原因:
1. .m2裡的jar包沒有下完全,刪了,然後update project

問題2:對於html檔案可以訪問,但Controller方法一直訪問不到,提示Whitelabel Error Page

原因:

1. 專案的啟動類放錯了位置,應當放在Controller註解的上一層,具體不是很懂,請指教

自定義持久化介面,配置檔案那裡多看幾遍

基本入門了,後面就該買書加深對細節的理解了。


參考:慕課網廖師兄:https://gitee.com/liaoshixiong/girl,感謝分享

看到個:http://blog.csdn.net/rickiyeat/article/details/77543445