spring test 启动加载不到配置文件的错误

  测试类代码:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring/spring.xml")
public class MyTest {
@Test
public void test1(){
    System.out.println(1);
}
}

(1)错误1:

报错:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:

Error creating bean with name 'qrcodeSocketHandler': Unsatisfied dependency expressed through field 'sRedis'; nested exception is org.springframework.beans.factory.BeanCreationException:

Error creating bean with name 'jedisCluster' defined in class path resource [spring/spring-redis.xml]:

Cannot create inner bean 'redis.clients.jedis.HostAndPort#7ea4d397' of type [redis.clients.jedis.HostAndPort] while setting constructor argument with key [0]; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:

Error creating bean with name 'redis.clients.jedis.HostAndPort#7ea4d397' defined in class path resource [spring/spring-redis.xml]:

Unsatisfied dependency expressed through constructor parameter 1: Could not convert argument value of type [java.lang.String] to required type [int]: Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: "${cluster.port1}"

 

原因是配置文件中的配置没有加载进来导致的。

我的spring.xml中之前是这样:

<context:property-placeholder location="classpath:*.properties" ignore-unresolvable="true"/>

导致test启动不了

 

改成

<context:property-placeholder location="classpath*:*.properties" ignore-unresolvable="true"/>

之后就应该成功了

原因:

  • 同名资源存在时,classpath: 只从第一个符合条件的classpath中加载资源,而classpath*: 会从所有的classpath中加载符合条件的资源
  • classpath*:需要遍历所有的classpath,效率肯定比不上classpath,因此在项目设计的初期就尽量规划好资源文件所在的路径,避免使用classpath*来加载

 

(2) 错误2:

我的项目比较特殊,出现了一个加载WebMvcConfigurationSupport类时报的错:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException:

No ServletContext set

 

意思是测试类启动的时候没有加载servletContext容器,

解决方法:在测试类上添加@WebAppConfiguration注释

最后成功启动

成功启动的测试类代码如下:

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/spring/spring.xml") @WebAppConfiguration public class MyTest { @Test public void test1(){ System.out.println(1); } }

 

 

参考文章:

1)https://blog.csdn.net/lebron3v/article/details/80608810

2)https://blog.csdn.net/liu_gan/article/details/78400627

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值