0
点赞
收藏
分享

微信扫一扫

springboot自定义配置文件


前面介绍了多环境配置文件,我们也可以使用自定义配置文件,比如新建一个test.properties,配置文件内容如代码

com.book.name=spring boot 2
com.book.author = yangyang

与之前一样,新建一个javabean来读取配置文件。新建一个ConfigBean,在类上加上注解@PropertySource(value = "classpath:test.properties"),并且和之前一样需要加入@ConfigurationProperties(prefix = "com.book"),实体类代码如代码

package com.shrimpking;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/12/21 10:01
 */
@Component
@PropertySource(value = "classpath:test.properties")
@ConfigurationProperties(prefix = "com.book")
public class TestConfigBean
{
    private String name;
    private String author;

    public String getName()
    {
        return name;
    }

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

    public String getAuthor()
    {
        return author;
    }

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

同样,在Controller中注入bean并且创建测试方法,内容如代码

package com.shrimpking;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/12/21 10:03
 */
@RestController
public class ConfigController
{
    @Autowired
    private TestConfigBean testConfigBean;

    @GetMapping("/test3")
    public TestConfigBean test3(){
        return  testConfigBean;
    }
}

使用浏览器访问http://localhost:8089/test3,可以看到显示如下内容:

springboot自定义配置文件_配置文件

举报

相关推荐

0 条评论