1. 程式人生 > 其它 >springboot-1-入門

springboot-1-入門

springboot-1-入門

1、springboot簡介,背景

簡化Spring應用開發的一個框架;

整個Spring技術棧的一個大整合;

J2EE開發的一站式解決方案;

2、極簡helloworld

流程:

使用spring initializr建立springboot新專案

在主程式的同級目錄下建立包

  • control包
  • dao包
  • pojo包
  • service包

建立一個control

@Controller
public class HelloController {

    @ResponseBody
    @RequestMapping("/hello")
    public String hello(){
        return "Hello World!";
    }
}

直接執行主程式即可

@SpringbootApplication

//@SpringBootApplication
//等與springboot的配置類 + 自動配置開啟 + 元件掃描範圍
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.wang")
public class SpringbootSpringboot1Application {

主程式原理

之前:

public class SpringbootSpringboot1Application {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootSpringboot1Application.class, args);
    }

}

之後:

public class MainApplication {
    public static void main(String[] args) {
        //1、返回IOC容器
        ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
        //2、檢視IOC容器中的bean
        String[] beanDefinitionNames = run.getBeanDefinitionNames();
        for (String i:beanDefinitionNames){
            System.out.println(i);
        }
        //3、從容器中獲取自定義的bean
        Pet pet = run.getBean("pet", Pet.class);
        System.out.println("pet------------>>>>>"+pet);
    }
}

可以理解為得到的run例項化物件就是一個IOC容器可以從裡面獲取到所有bean例項

3、yaml使用

流程:

匯入提示配置依賴

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>


 <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <!--這個提示包是開發工具,不需要打包-->
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-configuration-processor</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

建立pojo

@Data
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
	
	private String userName;
	private Boolean boss;
	private Date birth;
	private Integer age;
	private Pet pet;
	private String[] interests;
	private List<String> animal;
	private Map<String, Object> score;
	private Set<Double> salarys;
	private Map<String, List<Pet> allPets;
}

@Data
public class Pet {
	private String name;
	private Double weight;
}

對應的yaml檔案

# yaml表示以上物件
person:
  userName: zhangsan
  boss: false
  birth: 2019/12/12 20:12:33
  age: 18
  pet: 
    name: tomcat
    weight: 23.4
  interests: [籃球,游泳]
  animal: 
    - jerry
    - mario
  score:
    english: 
      first: 30
      second: 40
      third: 50
    math: [131,140,148]
    chinese: {first: 128,second: 136}
  salarys: [3999,4999.98,5999.99]
  allPets:
    sick:
      - {name: tom}
      - {name: jerry,weight: 47}
    health: [{name: mario,weight: 47}]

注意:

1、在添加了這個配置之後不會立刻出現提示,需要重啟專案

2、pojo類上加了@ConfigurationProperties(prefix = "person")之後必須要還要加上一個@Component,讓IOC容器能夠掃描到這個類

@ConfigurationProperties

該註解有一個prefix屬性,通過指定的字首,繫結配置檔案中的配置,該註解可以放在類上,也可以放在方法上

可以從註解說明中看到,當將該註解作用於方法上時,如果想要有效的繫結配置,那麼該方法需要有 @Bean 註解且所屬Class需要有 @Configuration 註解。

5\熱部署(dev-tool)

Restart VS Reload

<!--dev-tool-自動重啟,ctrl+F9快捷鍵自動重啟-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>

ctrl+F9快捷鍵快速重啟

如果需要真正的熱部署需要付費載入JRebel外掛

6\JSR303驗證

在pojo的類的對應屬性使用JSR303驗證的對應註解,可以保證無論哪種方式建立這個pojo都會進行這個註解的驗證,從而達到驗證的效果

@Data
@Validated
public class Person {
    private String name;
    private Integer age;
    /*驗證這個屬性是否為郵箱格式,message屬性為報錯資訊(預設為不是一個合法的郵箱格式*/
    @Email(message = "郵箱格式有誤")
    private String email;
}

還有其他驗證

Null檢查
@Null(message = "")       驗證物件是否為null
@NotNull(message = "")    驗證物件是否不為null, 無法查檢長度為0的字串
@NotBlank(message = "")   檢查約束字串是不是Null還有被Trim的長度是否大於0,只對字串,且會去掉前後空格.
@NotEmpty(message = "")  檢查約束元素是否為NULL或者是EMPTY.
 
Booelan檢查
@AssertTrue(message = "")     驗證 Boolean 物件是否為 true  
@AssertFalse(message = "")    驗證 Boolean 物件是否為 false  
 
長度檢查
@Size(min=, max=,message = "") 驗證物件(Array,Collection,Map,String)長度是否在給定的範圍之內  
@Length(min=, max=,message = "") Validates that the annotated string is between min and max included.
 
日期檢查
@Past(message = "")           驗證 Date 和 Calendar 物件是否在當前時間之前  
@Future(message = "")     	驗證 Date 和 Calendar 物件是否在當前時間之後  
@Pattern(regexp = "",message = "")    	驗證 String 物件是否符合正則表示式的規則
 
數值檢查
	建議使用在包裝型別(Integer這類),不建議使用在int型別上,
	因為表單值為“”時無法轉換為int,但可以轉換為Stirng為"",Integer為null
@Min(message = "")     驗證 Number 和 String 物件是否大等於指定的值  
@Max(message = "")     驗證 Number 和 String 物件是否小等於指定的值  
@DecimalMax(message = "") 值不大於約束中指定的最大值. 這個約束的引數是一個通過BigDecimal定義的最大值的字串表示.小數存在精度
@DecimalMin(message = "") 值必須不小於約束中指定的最小值. 這個約束的引數是一個通過BigDecimal定義的最小值的字串表示.小數存在精度
@Digits(message = "")     驗證 Number 和 String 的構成是否合法  
@Digits(integer=,fraction=,message = "") 驗證字串是否是符合指定格式的數字,interger指定整數精度,fraction指定小數精度。
 
@Range(min=, max=,message = "") 檢查數字是否介於min和max之間.

@Valid  遞迴的對關聯物件進行校驗, 如果關聯物件是個集合或者陣列,那麼對其中的元素進行遞迴校驗,如果是一個map,則對其中的值部分進行校驗.(是否進行遞迴驗證)
    
@CreditCardNumber(message = "") 信用卡驗證
@Email(message = "")  驗證是否是郵件地址,如果為null,不進行驗證,算通過驗證。
@ScriptAssert(lang= ,script=, alias=,message = "")
    
@URL(protocol=,host=, port=,regexp=, flags=,message = "")

7\多環境配置

properties檔案時:一個主要配置檔案,去呼叫另外倆(多)個配置檔案

yaml檔案時:用---分割程式碼塊,第一個程式碼塊去呼叫另外兩(多)個程式碼塊

properties作為配置檔案時

在resource下建立三個properties檔案:

  • application.properties
  • application-dev.properties
  • application-test.properties

application.properties檔案中配置我們需要的另外倆格配置檔案

#比如在配置檔案中指定使用dev環境,我們可以通過設定不同的埠號進行測試;
#我們啟動SpringBoot,就可以看到已經切換到dev下的配置了;
spring.profiles.active=dev

yaml作為程式碼塊時


server:
  port: 8081
#選擇要啟用那個環境塊
spring:
  profiles:
    active: prod
---
server:
  port: 8083
spring:
  profiles: dev #配置這個環境的名稱
---
server:
  port: 8084
spring:
  profiles: prod  #配置這個環境的名稱