【spring boot笔记】4.配置

从配置文件中获取值:

@Component
@ConfigurationProperties
@Validated // 选填

让类成为一个组件,然后通过配置文件获取值
@ConfigurationProperties 默认从全局配置文件中获取值
@Validateded 让属性满足一些条件
参考:https://blog.****.net/AXIMI/article/details/88650053

几种配置方式:

  • @ConfigurationProperties
  • @Propertysource
  • @ImportResource
  • 配置类

@ConfigurationProperties 默认从全局配置文件中获取值


@Propertysource:加载指定的文件,格式:

@Component
@Propertysource(value={“classpath: file1.properties”})


@ImportResource:导入spring的配置文件,使配置文件中的内容生效

配置类(Spring Boot推荐给容器中添加组件的方式):
首先在如下的路径中添加配置类文件MyAppConfig.java:
【spring boot笔记】4.配置
然后在该配置类文件中写入:

package com.demo.learning02.config;

import com.demo.learning02.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyAppConfig {
    //
    @Bean
    public HelloService helloService(){
        System.out.println("通过@Bean给容器中添加组件");
        return new HelloService();
    }
}

@Configuration表示该类为一个配置类,用于代替spring的配置文件
@Bean 将方法的返回值添加到容器中,容器中组件的默认id就是方法名


配置文件占位符

配置文件中的随机数
配置文件占位符