SpringBoot 注解@ConfigurationProperties和@Value和@Configration和@Bean

1.@ConfigurationProperties和@Value的区别
注解 @ConfigurationProperties @Value
功能 批量注入配置文件中的属性 一个个的指定
松散绑定(松散语法) 支持 不支持
SPEL 不支持 支持
JSR303数据校验 支持 不支持
复杂类型封装 支持 不支持
  • 配置文件yml还是properties他们都能获取到值
  • 如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value;
  • 如果说,我们专门编写了一个javaBean来和配置文件进行映射,我们就直接使用@ConfigurationProperties;
2.配置文件注入值校验和获得值方式
@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {
/**
* <bean class="Person">
* <property name="lastName" value="字面量/${key}从环境变量、配置文件中获取值/#
{SpEL}"></property>
* <bean/>
*/
//lastName必须是邮箱格式
@Email
//@Value("${person.last‐name}")
private String lastName;
//@Value("#{11*2}")
private Integer age;
//@Value("true")
private Boolean boss;

value获取配置文件中某个值

@RestController // RestAPI方式
@RequestMapping("/hello")
public class HelloController {
    
    @Value("${person.name}")
    private String name;
    
    @RequestMapping("/hello")
    public  String hello(){
        return name;
    }
}
3.@PropertySource&@ImportResource&@Bean

@PropertySource: 加载指定的配置文件
ConfigurationProperties: 默认加载全局配置文件

@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
public class Person {

@ImportResource:导入Spring的配置文件,让配置文件里面的内容生效;
Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别;
想让Spring的配置文件生效,加载进来;@ImportResource标注在一个配置类上

@ImportResource(locations = {"classpath:beans.xml"})
导入Spring的配置文件让其生效
3.SpringBoot推荐给容器中添加组件的方式;推荐使用全注解的方式
  • 配置类@Configuration------>Spring配置文件
  • 使用@Bean给容器中添加组件
  • 配置类如下:
/**
 * @Configuration: 指明当前类是一个配置类;就是来替代之前的Spring配置文件
 *                   在配置文件中用<bean><bean/>标签添加组件
 */
@Configuration
public class myApplicationConfig {
    // 将方法的返回值添加到容器中,容器中这个组件默认的id就是方法名:helloService
    @Bean
    public HelloService helloService(){
        System.out.println("配置类@Bean向容器中添加组件了。。。。。。。。");
        return new HelloService();
    }
}
  • 测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootHelloworldQuickApplicationTests {
	@Autowired
	ApplicationContext ioc;

	@Test
	public void testGetBean(){
		boolean flag = ioc.containsBean("helloService");
		System.out.println(flag);
	}
}
4.配置文件占位符
  • 随机数

${random.value}、${random.int}、${random.long}
${random.int(10)}、${random.int[1024,65536]}
  • 占位符
person.last‐name=张三${random.uuid}
person.age=${random.int}
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=${person.hello:hello}_dog
person.dog.age=15

猜你喜欢

转载自blog.csdn.net/m0_38068812/article/details/88083369