Spring Boot从入门到放弃-获取自定义配置

目录:

第一个程序 hello World

Spring Boot 关闭某些自动配置

Spring Boot 修改banner

Spring Boot 全局配置文件

Spring Boot 从入门到放弃-获取自定义配置

Spring Boot 整合测试

Spring Boot Application与Controller分离

Spring Boot 日志文件

Spring Boot 自定义日志文件

摘要:

      通过Spring注解获取配置文件中配置的全局变量。使用配置文件方便集中管理所有的配置。可以通过 @Value("${book.author}")获取,或者通过@ConfigurationProperties(prefix = "book"),属性名和配置名需要相同,但需要设置set和get方法。

Value案例:

application.properties 文件:

book.author = tom
book.name = Springboot
BookController.java文件:
package com.edu.usts.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@EnableAutoConfiguration
@Controller
public class BookController {
//  取自定义属性值
    @Value("${book.author}")
    private String author;

    @Value("${book.name}")
    private String name;

    @ResponseBody
    @RequestMapping("/bookinfo")
    public String showinfo(){
        return author+":"+name;
    }

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


}

页面显示:

成功获取配置文件中自定义数据。不要和预留关键字冲突。

ConfigurationProperties案例:

application.properties 文件不变。

BookController.java:

package com.edu.usts.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@EnableAutoConfiguration
@Controller
@ConfigurationProperties(prefix = "book")
public class BookController {


//  取自定义属性值
    private String author;

    private String name;

//    使用 ConfigurationProperties 开头,需要设置set、get方法
    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @ResponseBody
    @RequestMapping("/bookinfo")
    public String showinfo(){
        return author+":"+name;
    }

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


}

注: 使用@Value注入每个自定义配置在项目中显得很麻烦,数据量一大就难受了。Spring Boot提供了基于类型安全的配置方式即@ConfigurationProperties方式配置,将application.properties中的属性和一个Bean的属性关联。从而实现类型安全的配置。

源码gitee地址:

https://gitee.com/jockhome/springboot

发布了41 篇原创文章 · 获赞 108 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/qq_37857921/article/details/103406300
今日推荐