阅读 621

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

这篇文章主要介绍了SpringBoot 属性配置中获取值的方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

目录
  • SpringBoot 属性配置中获取值

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

    • 测试和生产区分

  • SpringBoot 获取值和配置文件

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

    • 2、@Value方式

    • 3、@PropertySource

    • 4、@ImportResource和@Bean

SpringBoot 属性配置中获取值

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

appliaction.yml:

1
2
3
4
server:
  port: 8081
cubSize: B
age: 18

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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 文件

1
2
3
4
5
server:
  port: 8081
gril:
  name: lisa
  height: 165

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

GrilProperties实体:

注意我们用到了这个注解:@ConfigurationProperties(prefix = “gril”)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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中发现会有红线出现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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注解了。

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

1
2
3
4
5
server:
  port: 8081
cubSize: B
age: 18
context: "cubSize:${cubSize},age:${age}"

这种情况证明获取的属性值呢?

在controller中编码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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 文件中这样写:

1
2
3
spring:
  profiles:
    active: prod

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

SpringBoot 获取值和配置文件

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@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配置文件:


1
2
3
4
5
6
7
8
9
10
student:
  sname: zhai
  age: 12
  maps: {k1: 12,k2: 13}
  list:
    - zhai
    - zhang
  course:
    courseno: 202007
    coursename: javaweb

(3)创建properties文件:

1
2
3
4
5
6
7
8
#配置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)测试类:

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

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

1
2
3
4
5
   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <version>2.2.1.RELEASE</version>
   </dependency>

2、@Value方式

(1)书写配置文件

1
2
3
4
5
6
7
8
#配置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)获取值:

1
2
3
4
5
6
7
8
9
10
11
@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校验

1
2
3
4
5
6
7
8
9
10
11
@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 = "")方式

1
2
3
4
5
6
7
8
9
@RestController
public class HelloController {
    @Value("${student.sname}")
    private String sname;
    @RequestMapping("/hello")
    public String hello(){
        return "hello"+sname;
    }
}

配置文件:

1
2
3
4
5
6
7
8
#配置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)

1
2
3
4
5
6
7
8
#配置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)实体类获取值

1
2
3
4
5
6
7
8
9
10
@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的配置文件

1
2
3
4
5
6
7
@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)书写如下配置,可以省略配置文件的书写,用注解来代替

1
2
3
4
5
6
7
@Configuration
public class MyAppConfig {
    @Bean
    public HelloService helloService(){
        return new HellService();
    }
}

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

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

总结:

(1)@ConfigurationProperties与@Value

以上为个人经验,希望能给大家一个参考

原文链接:https://blog.csdn.net/xusheng_Mr/article/details/79602063


文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐