@Value获取值和@ConfigurationProperties获取值比较
@ConfigurationProperties | @Value |
---|---|
批量注入配置文件中的属性 | 一个个指定 |
支持松散语法绑定 | 不支持松散语法绑定 |
不支持SpEL(计算) | 支持SpEL(计算) |
支持JSR303数据校验(判断键值的赋值是否符合要求格式) | 不支持() |
支持复杂类型封装 | 不支持 |
配置文件yml还是properties他们都能获取到值:
如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的单项值,使用@Value;如果说,我们专门编写了一个javaBean来和配置文件进行映射,使用@ConfigurationProperties
@PropertySource和@ImportResource
@PropertySource:直接加载指定的配置文件;
@ImportResource;导入Spring的配置文件,让配置文件里面的内容生效
Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别;
想让Spring的配置文件生效,加载进来;@ImportResource标注在主配置类上
@ImportResource(locations = {"classpath:beans.xml"})
导入Spring的配置文件让其生效
不来编写Spring的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloService" class="com.atguigu.springboot.service.HelloService.java"></bean>
</beans>
SpringBoot推荐给容器中添加组件的方式:推荐使用全注解的方式
1、配置类====Spring配置文件
2、使用@Bean类来给容器中添加组件