通过springboot的5种读取配置方式(1):直接读取bean
springboot的5种读取配置方式(2):通过config读取指定文件
springboot的5种读取配置方式(3):通过application.properties读取
springboot的5种读取配置方式(4):通过application.yml读取
springboot的5种读取配置方式(5):通过applicationContext.xml读取
需要在实体类中声明@Configuration
读取文件是通过@ComponentScan()
比如:
//默认从根目录扫描 @Configuration
//扫描指定包路径 @ComponentScan("springboot.config")
读取文件都是通过@PropertySource()
比如:
.properties文件的格式是key=value
.yml文件格式是key:value
student.name= 小康 student.age=15
#yml文件的配置格式是key:value student: name: 小明 age : 25
@Value("${student.name}") private String name; @Value("${student.age}") private int age;
//读取resources目录下的application.properties @PropertySource("classpath:application.properties")
//读取resources目录下的application.yml @PropertySource("classpath:application.yml")
需要在pom.xml添加依赖:
<!-- 这个依赖会把配置文件的值注入到@value里面 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> </dependency>
比如:
默认读取的是application.properties文件里的信息。
但我把application.xml改名为applicationContext.xml时运行就正常了。
//读取resources目录下的applicationContext.xml @ImportResource("classpath:applicationContext.xml")我的座右铭:不会,我可以学;落后,我可以追赶;跌倒,我可以站起来;我一定行。