溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

SpringBoot屬性配置中獲取值的方式是什么

發(fā)布時(shí)間:2022-02-14 13:38:41 來(lái)源:億速云 閱讀:165 作者:iii 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹“SpringBoot屬性配置中獲取值的方式是什么”的相關(guān)知識(shí),小編通過(guò)實(shí)際案例向大家展示操作過(guò)程,操作方法簡(jiǎn)單快捷,實(shí)用性強(qiáng),希望這篇“SpringBoot屬性配置中獲取值的方式是什么”文章能幫助大家解決問(wèn)題。

SpringBoot 屬性配置中獲取值

在配置文件中定義屬性的值,然后再獲取,在這里做一個(gè)總結(jié),首先,在application.yml文件中定義端口和屬性的值,當(dāng)然,在.application.properties文件中也能定義,只是格式不同而已:

appliaction.yml:

server:
  port: 8081
cubSize: B
age: 18

然后再定義一個(gè)controller,用@Value這個(gè)注解來(lái)獲取到值:

package com.dist.tr.controller;
import com.dist.tr.entity.GrilProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping
public class BeautifulGirlContrller {
    @Value("${cubSize}")
    private String cubSize;
    @Value("${age}")
    private Integer age;
    @RequestMapping(value = "/gril",method = RequestMethod.GET)
    public String HelloGril(){
        return cubSize + age;
    }
}

運(yùn)行結(jié)果:

SpringBoot屬性配置中獲取值的方式是什么

如果當(dāng)屬性很多之后,要寫(xiě)很多的@Value 的注解嘛???答案當(dāng)然是No,有簡(jiǎn)便的寫(xiě)法:

application.yml 文件

server:
  port: 8081
gril:
  name: lisa
  height: 165

首先,定義一個(gè)實(shí)體類(lèi)去寫(xiě)屬性

GrilProperties實(shí)體:

注意我們用到了這個(gè)注解:@ConfigurationProperties(prefix = “gril”)

package com.dist.tr.entity;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "gril")
public class GrilProperties {
    private String name;
    private String height;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getHeight() {
        return height;
    }
    public void setHeight(String height) {
        this.height = height;
    }
}

在controller 中的寫(xiě)法:

首先用注解@Autowired 注入這個(gè)實(shí)體,如果不在實(shí)體中加@Component這個(gè)注解,在idea中發(fā)現(xiàn)會(huì)有紅線出現(xiàn)。

package com.dist.tr.controller;
import com.dist.tr.entity.GrilProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping
public class BeautifulGirlContrller {
    @Autowired
    private GrilProperties grilProperties;
    @RequestMapping("/grilPerproties")
    public String grilPerproties(){
        return grilProperties.getName()+grilProperties.getHeight();
    }
}

運(yùn)行結(jié)果:

SpringBoot屬性配置中獲取值的方式是什么

這樣就不會(huì)需要去寫(xiě)太多的@Value注解了。

還有中形式,就是在配置文件中也可以有這種情況出現(xiàn):

server:
  port: 8081
cubSize: B
age: 18
context: "cubSize:${cubSize},age:${age}"

這種情況證明獲取的屬性值呢?

在controller中編碼:

package com.dist.tr.controller;
import com.dist.tr.entity.GrilProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping
public class BeautifulGirlContrller {
    @Value("${context}")
    private String context;
    @RequestMapping("/grilSize")
    public String girlcubSize(){
        return context ;
    }
}

運(yùn)行結(jié)果:

SpringBoot屬性配置中獲取值的方式是什么

測(cè)試和生產(chǎn)區(qū)分

當(dāng)在項(xiàng)目開(kāi)發(fā)的時(shí)候,如果區(qū)分測(cè)試和生產(chǎn)環(huán)境,那么就得區(qū)分開(kāi)application.yml 文件:

新建application-dev.yml 文件和application-prod.yml文件:

然后在使用測(cè)試或者是生產(chǎn)的時(shí)候,application.yml 文件中這樣寫(xiě):

spring:
  profiles:
    active: prod

決定是用測(cè)試環(huán)境還是生產(chǎn)環(huán)境。

SpringBoot 獲取值和配置文件

@ConfigurationProperties、@Value、@PropertySource、@ImportResource和@Bean

1、@ConfigurationProperties(prefix = "student")方式

(1)定義兩個(gè)實(shí)體類(lèi),其中student實(shí)體類(lèi)的屬性包括Course類(lèi):

@Data
@Component
@ConfigurationProperties(prefix = "student")//告訴springboot將本類(lèi)中的所有屬性和配置文件的相關(guān)配置進(jìn)行綁定
public class Student {       //prefix:配置文件中哪一個(gè)名稱下面的屬性進(jìn)行一一映射
    private String sname;
    private int age;
    private Map<String,Object> maps;
    private List<Object> list;
    private Course course;
}
@Data
public class Course {
    private String courseno;
    private String coursename;
}

(2)創(chuàng)建yaml配置文件:

student:
  sname: zhai
  age: 12
  maps: {k1: 12,k2: 13}
  list:
    - zhai
    - zhang
  course:
    courseno: 202007
    coursename: javaweb

(3)創(chuàng)建properties文件:

#配置student
student.age=12
student.sname=zhai
student.maps.k1=1
student.maps.k2=2
student.list=a,b,c
student.course.courseno=202007
student.course.coursename=java

(4)測(cè)試類(lèi):

//可以在測(cè)試期間很方便地類(lèi)似編碼一樣進(jìn)行自動(dòng)注入等容器的功能
@SpringBootTestclass Springboot03ApplicationTests {
    @Autowired
    Student student;
    @Test
    void contextLoads() {
        System.out.println(student);
    }
}

(5)需要導(dǎo)入的依賴:配置文件處理器,配置文件進(jìn)行綁定會(huì)有提示

   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <version>2.2.1.RELEASE</version>
   </dependency>

SpringBoot屬性配置中獲取值的方式是什么

2、@Value方式

(1)書(shū)寫(xiě)配置文件

#配置student
student.sname=zhai
student.age=12
student.maps.k1=1
student.maps.k2=2
student.list=a,b,c
student.course.courseno=202007
student.course.coursename=java

(2)獲取值:

@Data
@Component
public class Student {
    @Value("${student.sname}")
    private String sname;
    @Value("#{2*9}")
    private int age;
    private Map<String,Object> maps;
    private List<Object> list;
    private Course course;
}

(3)@ConfigurationProperties(prefix = "")方式與@Value方式的比較

  • @ConfigurationProperties(prefix = "")方式支持批量注入配置文件的屬性,@Value方式需要一個(gè)個(gè)指定

  • @ConfigurationProperties(prefix = "")方式支持松散綁定,@Value方式不支持,

yml中寫(xiě)的last-name,這個(gè)和lastName是一樣的,后面跟著的字母默認(rèn)是大寫(xiě)的。這就是松散綁定

@Value方式支持JSR303校驗(yàn)

@Data
@Component
@Validated
public class Student {
    @NonNull
    private String sname;
    private int age;
    private Map<String,Object> maps;
    private List<Object> list;
    private Course course;
}

@Value方式支持SpEl

如果我們只是在某一個(gè)業(yè)務(wù)邏輯中需要獲取配置文件的某一項(xiàng)值,可以使用@Value,如果是一個(gè)javaBean來(lái)和配置文件進(jìn)行映射,則要使用@ConfigurationProperties(prefix = "")方式

@RestController
public class HelloController {
    @Value("${student.sname}")
    private String sname;
    @RequestMapping("/hello")
    public String hello(){
        return "hello"+sname;
    }
}

配置文件:

#配置student
student.sname=zhai
student.age=12
student.maps.k1=1
student.maps.k2=2
student.list=a,b,c
student.course.courseno=202007
student.course.coursename=java

3、@PropertySource

(1)配置文件(student.properties)

#配置student
student.sname=zhai
student.age=12
student.maps.k1=1
student.maps.k2=2
student.list=a,b,c
student.course.courseno=202007
student.course.coursename=java

(2)實(shí)體類(lèi)獲取值

@Data
@Component
@PropertySource(value = {"classpath:student.properties"})
public class Student {
    private String sname;
    private int age;
    private Map<String,Object> maps;
    private List<Object> list;
    private Course course;
}

@PropertySource是從指定路徑下獲取數(shù)據(jù),默認(rèn)是從application.properties下獲取數(shù)據(jù)

4、@ImportResource和@Bean

(1)指定spring的配置文件

@SpringBootApplication(scanBasePackages = "com")
@ImportResource(locations = {"classpath:beans.xml"})
public class Springboot02Application {
    public static void main(String[] args) {
        SpringApplication.run(Springboot02Application.class, args);
    }
}

(2)書(shū)寫(xiě)spring的配置文件:beans.xml

(3)書(shū)寫(xiě)如下配置,可以省略配置文件的書(shū)寫(xiě),用注解來(lái)代替

@Configuration
public class MyAppConfig {
    @Bean
    public HelloService helloService(){
        return new HellService();
    }
}

@Configuration說(shuō)明這是一個(gè)配置類(lèi),就是在替代之前的配置文件

@Bean標(biāo)記在方法上,該方式將方法的返回值添加到容器中,容器中組件的ID默認(rèn)是方法名

關(guān)于“SpringBoot屬性配置中獲取值的方式是什么”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI