SpringBoot 属性配置中获取值的方式

目录
  • SpringBoot 属性配置中获取值
    • 首先,定义一个实体类去写属性
    • 测试和生产区分
  • SpringBoot 获取值和配置文件
    • 1、@ConfigurationProperties(prefix = "student")方式
    • 2、@Value方式
    • 3、@PropertySource
    • 4、@ImportResource和@Bean

SpringBoot 属性配置中获取值

在配置文件中定义属性的值,然后再获取,在这里做一个总结,首先,在application.yml文件中定义端口和属性的值,当然,在.application.properties文件中也能定义,只是格式不同而已:

appliaction.yml:

server:
  port: 8081
cubSize: B
age: 18

然后再定义一个controller,用@Value这个注解来获取到值:

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;
    }
}

运行结果:

如果当属性很多之后,要写很多的@Value 的注解嘛???答案当然是No,有简便的写法:

application.yml 文件

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

首先,定义一个实体类去写属性

GrilProperties实体:

注意我们用到了这个注解:@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 中的写法:

首先用注解@Autowired 注入这个实体,如果不在实体中加@Component这个注解,在idea中发现会有红线出现。

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();
    }
}

运行结果:

这样就不会需要去写太多的@Value注解了。

还有中形式,就是在配置文件中也可以有这种情况出现:

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 ;
    }
}

运行结果:

测试和生产区分

当在项目开发的时候,如果区分测试和生产环境,那么就得区分开application.yml 文件:

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

然后在使用测试或者是生产的时候,application.yml 文件中这样写:

spring:
  profiles:
    active: prod

决定是用测试环境还是生产环境。

SpringBoot 获取值和配置文件

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

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

(1)定义两个实体类,其中student实体类的属性包括Course类:

@Data
@Component
@ConfigurationProperties(prefix = "student")//告诉springboot将本类中的所有属性和配置文件的相关配置进行绑定
public class Student {       //prefix:配置文件中哪一个名称下面的属性进行一一映射
    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)创建yaml配置文件:

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

(3)创建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)测试类:

//可以在测试期间很方便地类似编码一样进行自动注入等容器的功能
@SpringBootTestclass Springboot03ApplicationTests {
    @Autowired
    Student student;
    @Test
    void contextLoads() {
        System.out.println(student);
    }
}

(5)需要导入的依赖:配置文件处理器,配置文件进行绑定会有提示

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

2、@Value方式

(1)书写配置文件

#配置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方式需要一个个指定
  • @ConfigurationProperties(prefix = "")方式支持松散绑定,@Value方式不支持,

yml中写的last-name,这个和lastName是一样的,后面跟着的字母默认是大写的。这就是松散绑定

@Value方式支持JSR303校验

@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

如果我们只是在某一个业务逻辑中需要获取配置文件的某一项值,可以使用@Value,如果是一个javaBean来和配置文件进行映射,则要使用@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)实体类获取值

@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是从指定路径下获取数据,默认是从application.properties下获取数据

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)书写spring的配置文件:beans.xml

(3)书写如下配置,可以省略配置文件的书写,用注解来代替

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

@Configuration说明这是一个配置类,就是在替代之前的配置文件

@Bean标记在方法上,该方式将方法的返回值添加到容器中,容器中组件的ID默认是方法名

总结:

(1)@ConfigurationProperties与@Value

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • SpringBoot 如何从配置文件读取值到对象中

    目录 一.实现方式 @ConfigurationProperties 注解 @Valid注解 二.两者区别 三.代码演示 四.@PropertySource 读取指定配置文件 五.@ImportResource:导入Spring配置文件 六.思维导图 一.实现方式 @ConfigurationProperties 注解 (最好加上前缀prefix="person",标明是和配置文件中哪个开头的属性匹配) 推荐使用用在类上,从配置文件读取属性值,放到对象里面,复杂的结构也适用例如map,

  • Spring Boot读取配置属性常用方法解析

    1. 前言 在Spring Boot项目中我们经常需要读取application.yml配置文件的自定义配置,今天就来罗列一下从yaml读取配置文件的一些常用手段和方法. 2. @Value 首先,会想到使用@Value注解,该注解只能去解析yaml文件中的简单类型,并绑定到对象属性中去. felord: phone: 182******32 def: name: 码农小胖哥 blog: felord.cn we-chat: MSW_623 dev: name: 码农小胖哥 blog: felo

  • 详解SpringBoot读取配置文件的N种方法

    我们在项目开发中经常会用到配置信息,例如数据库连接的帐号.密码等,而为了方便维护,我们通常将这些信息放到配置文件中.在需要用到这些配置信息时,可以通过代码获取.下面我们看看Spring中有哪些获取配置信息的方法. PropertiesLoaderUtils读取 通过ClassPathResource加载配置文件资源,结合PropertiesLoaderUtils类读取,源码如下: ClassPathResource resource = new ClassPathResource("applic

  • springboot如何读取配置文件(application.yml)中的属性值

    在spring boot中,简单几步,读取配置文件(application.yml)中各种不同类型的属性值: 1.引入依赖: <!-- 支持 @ConfigurationProperties 注解 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId>

  • SpringBoot 属性配置中获取值的方式

    目录 SpringBoot 属性配置中获取值 首先,定义一个实体类去写属性 测试和生产区分 SpringBoot 获取值和配置文件 1.@ConfigurationProperties(prefix = "student")方式 2.@Value方式 3.@PropertySource 4.@ImportResource和@Bean SpringBoot 属性配置中获取值 在配置文件中定义属性的值,然后再获取,在这里做一个总结,首先,在application.yml文件中定义端口和属性

  • 在SpringBoot 中从application.yml中获取自定义常量方式

    要注意的地方是 application.yml 中不能用驼峰式写法(systemParams)要改成system-params 方法一: 引入依赖: <!-- 支持 @ConfigurationProperties 注解 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</a

  • Spring的@Value如何从Nacos配置中心获取值并自动刷新

    目录 @Value从Nacos配置中心获取值并自动刷新 Nacos属性值自动刷新 1.@NacosValue获取最新值 2.@Value获取最新值 @Value从Nacos配置中心获取值并自动刷新 在使用Nacos作为配置中心时,除了@NacosValue可以做到自动刷新外,nacos-spring-context:0.3.4版本是支持@Value获取Nacos配置中心的值,并动态刷新的,该功能是Spri依靠ngValueAnnotationBeanPostProcessor类来实现: @Ove

  • 解决Properties属性文件中的值有等号和换行的小问题

    目录 Properties属性文件中的值有等号和换行 Properties属性文件可以这样写 处理properties文件中key包含空格和等号的情况 处理方案 Properties属性文件中的值有等号和换行 Spring配置Shiro的过滤器时,有个filterChainDefinitions属性,值中有等号有换行,尝试写到Properties属性文件中遇到问题 <!-- 配置shiro过滤器 --> <bean id="shiroFilter" class=&qu

  • spring框架下@value注解属性static无法获取值问题

    目录 @value注解属性static无法获取值 解决办法 @Value注解取不到值的几种情况 几种获取不到值的特殊情况如下 @value注解属性static无法获取值 @Value("${appId}") private static String appid; 这样是无法直接获得值的 解决办法 需要这样写 private static String appid; @Value("${appId}") public void setAppid(String app

  • easy ui datagrid 从编辑框中获取值的方法

    如下所示: var editors = $('datagrid的id').datagrid('getEditors', rowIndex); //rowIndex 行编号,从0算起 console.info(editors[0].target.val()); 以上这篇easy ui datagrid 从编辑框中获取值的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们.

  • SpringBoot从配置文件中获取属性的四种方法总结

    目录 方式一:@Value 方式二:@ConfigurationProperties @Value和@ConfigurationProperties比较 方式三:@PropertySource 方式四:使用工具类无需注入获取.yml中的值 方式一: @Value 基本类型属性注入,直接在字段上添加@Value("${xxx.xxx}")即可.注意这里用的是$,而不是#.@Value注入的属性,一般其他属性没有关联关系. 配置文件 user: name: Manaphy age: 19

  • 三种AngularJS中获取数据源的方式

    在AngularJS中,可以从$rootScope中获取数据源,也可以把获取数据的逻辑封装在service中,然后注入到app.run函数中,或者注入到controller中.本篇就来整理获取数据的几种方式. ■ 数据源放在$rootScope中 var app = angular.module("app",[]); app.run(function($rootScope){ $rootScope.todos = [ {item:"",done:true}, {it

  • Filter中获取传递参数方式(解决post请求参数问题)

    目录 Filter中获取传递参数 1. GET 传递 2. Post 传递 XyRequestWrapper 类 XySecurityFilter Filter中获取传递参数 1. GET 传递 参数可以直接通过request.getParameter获取. 2. Post 传递 产生不能过直接从request.getInputStream() 读取,必须要进行重新写.(request.getInputStream()只能够读取一次) 方式: 通过重写 HttpServletRequestWra

  • 在js中单选框和复选框获取值的方式

    复制代码 代码如下: // JavaScript Document function sub1() {      // 用Form名称直接引用form对象 //form1.method = "get"; // 将form名称作为document对象的属性来引用form对象, // 并用user作为form对象的属性来引用名为user的文本框元素对象 // document.form1.user.value = "lisi";              var s1=

随机推荐