Spring:单测及各种问题集锦

20 篇文章 0 订阅
  1. 如何脱离Spring boot环境(非@SpringbootTest)加载application.properties/yml
    import org.junit.Assert;
    import org.junit.jupiter.api.Test;
    import org.junit.jupiter.api.extension.ExtendWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
    import org.springframework.context.annotation.Import;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.TestPropertySource;
    import org.springframework.test.context.junit.jupiter.SpringExtension;
    
    // 脱离springboot启动环境如何加载属性文件
    @Import(value = {TestProperties.class})
    @EnableConfigurationProperties
    @ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)
    // 指定属性文件名字(可逗号分隔写多个)
    @TestPropertySource(properties = {"spring.config.name=test"})
    @ExtendWith(SpringExtension.class)
    public class NonBootButLoadPropertiesTest {
        @Autowired
        private TestProperties testProperties;
    
        @Test
        public void test() {
            Assert.assertEquals("frsh", testProperties.getValue());
        }
    }
    @Getter
    @Setter
    @Configuration
    @ConfigurationProperties(prefix = "test")
    public class TestProperties {
        private String value;
    }
    test:
      value: test-val

     

    说明:

    1. SpringExtension是spring-test包下,启动Spring容器环境的注解

    2. @TestPropertySource(properties = {"spring.config.name=test"})是指定将要加载的属性文件的名字

    3. @ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)是spring-test包下,为了加载属性文件专门的启动器

    4. 同样,@EnableConfigurationProperties不能缺少,包含解析上一步加载过来的文件内容到bean的属性中的处理器(应用binder将属性绑定到bean中)

    5.  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值