005 配置文件属性注入

一.概述

  在前面了解了yml文件的基本语法,在我们日常的使用过程之中,最为常见的一个功能就是将属性文件之中的值映射到IOC之中的bean的属性之中.

  springboot为我们提供了两种方式实现.

  @ConfigurationProperties和@Value注解来完成.


 二 .@ConfigurationProperties注解

  我们首先在配置文件之中定义这样的配置信息:

 

@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
@ConfigurationProperties(prefix="person")
public class Person {

    private String name;

    private Integer age;
}

我们编写上面的配置类,注意一个问题,我们需要制定前缀,另外就是我们的name和age正好与配置文件一致.

我们如果想使用这个注解:需要引入一个jar文件.

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

我们进行单元测试:  

@SpringBootTest(classes= {SpringbootApplicationStarter.class})
@RunWith(SpringRunner.class)
public class PropertiesTest {

    @Autowired
    private Person person;
    
    @Test
    public void test() {
        System.out.println(person);
    }
}

我们发现,我们的属性被正确赋值上去了.


 三 @value注解 

@Component
@Data
public class ConfigProperties {

    @Value("${jdbc.url}")
    private String url;
    
}
    @Autowired
    private ConfigProperties config;
    
    @Test
    public void test1() {
        System.out.println(config.getUrl());
    

我们发现我们使用spel也能正确的注入想要的值.

猜你喜欢

转载自www.cnblogs.com/trekxu/p/9452533.html
005