面試題 SpringBoot自定義starter

2021-09-23 14:25:46 字數 2986 閱讀 3609

1 新建module hello-spring-boot-starter

繼承 spring-boot-starter-parent

<?xml version="1.0" encoding="utf-8"?>

4.0.0

com.cdchen

hello-spring-boot-starter

1.0-snapshot

org.springframework.boot

spring-boot-starter-parent

1.5.6.release

utf-8

utf-8

1.8org.springframework.boot

spring-boot-starter

org.springframework.boot

spring-boot-starter-test

test

org.springframework.boot

spring-boot-configuration-processor

true

2 建立讀取配置pojo,helloserviceproperteis 指定字首
import org.springframework.boot.context.properties.configurationproperties;

@configurationproperties(prefix="cdchen")

public class helloserviceproperteis

public void setmsg(string msg)

}

3 建立測試服務類 helloservice
public class helloservice 

public string getmsg()

public void sayhello()

}

4 重中之重,建立自動配置類,helloautoconfiguration
import org.springframework.beans.factory.annotation.autowired;

import org.springframework.boot.autoconfigure.condition.conditionalonclass;

import org.springframework.boot.autoconfigure.condition.conditionalo****singbean;

import org.springframework.boot.autoconfigure.condition.conditionalonproperty;

import org.springframework.boot.context.properties.enableconfigurationproperties;

import org.springframework.context.annotation.bean;

import org.springframework.context.annotation.configuration;

@configuration

@enableconfigurationproperties(value = helloserviceproperteis.class)

@conditionalonclass(helloservice.class)

@conditionalonproperty(prefix = "cdchen", value = "enable", matchifmissing = true)

public class helloautoconfiguration

}

@configuration:標識此類為乙個spring配置類

@enableconfigurationproperties(value = helloserviceproperteis.class):啟動配置檔案,value用來指定我們要啟用的配置類,可以有多個,多個時我們可以這麼寫value=

@conditionalonclass(helloservice.class):表示當classpath下存在helloservice.class檔案時改配置檔案類才有效

@conditionalonproperty(prefix = 「cdchen」, value = 「enable」, matchifmissing = true):表示只有我們的配置檔案是否配置了以hello為字首的資源項值,並且在該資源項值為enable,如果沒有配置我們預設設定為enable

如果 enable設定false 則出現下面情況

5 指定引導類 在resources資料夾下新建 meta-inf資料夾,並在該資料夾下新建檔案spring.factories

內容為:org.springframework.boot.autoconfigure.enableautoconfiguration=com.cdchen.helloautoconfiguration

6 使用starter 在 springboot 專案中引入

com.cdchen

hello-spring-boot-starter

1.0-snapshot

7 增加配置檔案
cdchen.msg=wo shi hello service
8 啟動測試
@component

@autowired

private helloservice helloservice;

@override

public int getorder()

@override

helloservice.sayhello();}}

Spring Boot 相關面試題

spring boot swagger2 問 什麼是spring profiles?你如何使用spring boot實現它?a spring profiles允許使用者根據配置檔案 dev,test,prod等 註冊bean。因此,當應用程式在開發中執行時,只能載入某些bean,而在producti...

springboot面試題(基礎)

對映請求用什麼註解?index 指定引數用什麼註解?requestparam 如 public void queryusername requestparam value username required false string username 如何返回rest風格的資料?方法上加 respo...

Spring Boot 外部配置相關面試題

springboot 對外部配置提供了支援,允許我們在不同環境中執行相同的應用。我們可以使用 properties 檔案 yaml 檔案 環境變數 系統引數和命令列選項引數來宣告配置屬性。然後我們可以通過 value 這個通過 configurationproperties 繫結的物件的註解或者實現...