侧边栏壁纸
  • 累计撰写 251 篇文章
  • 累计创建 138 个标签
  • 累计收到 16 条评论

目 录CONTENT

文章目录

Spring Boot学习1——配置文件

Sherlock
2017-05-08 / 0 评论 / 0 点赞 / 1231 阅读 / 4492 字 / 编辑
温馨提示:
本文最后更新于 2023-10-09,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

1.读取核心配置文件

核心配置文件是指在 resources 根目录下的 application.propertiesapplication.yml 配置文件,读取这两个配置文件的方法有两种,都比较简单。

核心配置文件 application.properties 内容如下:

server.port=9090  
test.msg=Hello World Springboot!  

2.使用@Value方式(常用):

@RestController
public class WebController {

    @Value("${test.msg}")
    private String msg;

}

注意:在 @Value${} 中包含的是核心配置文件中的键名。

对于静态变量无法使用@Value赋值,可以曲线救国:

@Component
public class FileUtils {  
    private static String location;

    // 静态变量可以这样注入配置值
    @Value("${xxx.location}")
    public void setLocation(String location) {
        FileUtils.location = location;
    }
}

3.使用Environment方式

@RestController
public class WebController {  
    @Autowired
    private Environment env;

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index2() {
        return env.getProperty("test.msg");
    }
}

注意:这种方式是依赖注入 Evnironment 来完成,使用 @Autowired 注解即可完成依赖注入,然后使用 env.getProperty("key") 即可读取出对应的值。

4.读取自定义配置文件

例如在 resources/conf 目录下创建配置文件 sherlocky.properties 文件内容如下:

sherlocky.name=sherlock  
sherlocky.version=1.0.0  
...

需要一个管理配置的实体类:

@ConfigurationProperties(locations = "classpath:conf/sherlocky.properties", prefix = "sherlocky")
@Component
public class MyWebConfig {  
    private String name;
    private String version;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getVersion() {
        return version;
    }
    public void setVersion(String version) {
        this.version = version;
    }
}

注意@ConfigurationProperties 注解有两个属性:

  • locations:指定配置文件的所在位置
  • prefix:指定配置文件中键名称的前缀

该类添加了 @Component 注解,就可以使用 @Autowired 将该配置类注入到别的类使用。

4.1 绑定属性配置

注意:@ConfigurationProperties注解并没有把当前类注册成为一个 Spring 的 Bean,将其注入大致有三种方式:

  • 1.配合使用@Component注解直接进行注入。
@ConfigurationProperties(prefix = "sherlocky")
@Component
public class SherlockyProperties {  
    // 代码...
}
  • 2.使用@EnableConfigurationProperties注解,通常配置在标有@Configuration的类上,当然其他@Component注解的派生类也可以,不过不推荐。
@ConfigurationProperties(prefix = "sherlocky")
public class SherlockyProperties {  
    // 代码...
}
@EnableConfigurationProperties(SherlockyProperties.class)
@Configuration
public class SherlockyConfiguration {  
    // 代码...
}
  • 3.使用@Bean方式在标有@Configuration的类中进行注入,这种方式通常可以用在对第三方类进行配置属性注册的情况。
public class SherlockyProperties {  
    // 代码...
}
@Configuration
public class SherlockyConfiguration {  
    @ConfigurationProperties("sherlocky")
    @Bean
    public SherlockyProperties sherlockyProperties() {
        return new SherlockyProperties();
    }
}

参考:Spring Boot 2.0 @ConfigurationProperties 使用

0
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区