spring实战4 Failed to load ApplicationContext

今天看到spring的自动装配组件,照着书上的敲了下来报错了

代码:

接口

public interface CompactDisc {

    void play();
}
实现类

import org.springframework.stereotype.Component;

@Component
public class SgtPeppers implements CompactDisc {

private String title = "命运交响曲";
private String artist = "Ludwig van Beethoven";
@Override
public void play() {
System.out.println("player:"+title+ " by " +artist);
}
}

配置类
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
public class CDPlayerConfig {
}

测试类

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.assertNotNull;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CDPlayerConfig.class)
public class CDPlayerTest {

@Autowired
private CompactDisc cd;

@Test
public void cdShouldNotBeNull(){
assertNotNull(cd);
}

}

jdk1.7,spring4.3

然后执行测试类,错误

Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in class path resource

[org/springframework/scheduling/annotation/ProxyAsyncConfiguration.class]: Bean instantiation via factory method failed; nested exception

is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.scheduling.annotation.AsyncAnnotatio

nBeanPostProcessor]: Factory method 'asyncAdvisor' threw exception; nested exception is java.lang.IllegalArgumentException:

@EnableAsync annotation metadata was not injected

类中的方法 cdShouldNotNull,错误

java.lang.IllegalStateException: Failed to load ApplicationContext

错误是加载不到配置文件,明明用的javaconfig代替了xml文件了

@ContextConfiguration(classes = CDPlayerConfig.class)
这是怎么回事,于是,我创建了一个ApplicationContext就试着写成了
@ContextConfiguration(value = "classpath:/ApplicationContext.xml")
方法报错,这次和上次不一样了,ApplicationContext加载到了,但是又无法创建bean了
Error creating bean with name 'CDPlayerTest': Unsatisfied dependency expressed through field 'cd';
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type
'CompactDisc' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}
于是写成....
@ContextConfiguration(locations = {"classpath:/ApplicationContext.xml","classpath:/CDPlayerConfig.java"})
还是报错...
最后发现,是因为我把这几个类直接放到了src文件夹下的缘故,
解决方法:
把这些类都放到了新建的一个三级包下。书上的示例代码确实是放在了包下,这一点我没有注意,但也没想到这会有影响,细节还是很重要。

新人起步!欢迎指正!

 

posted @ 2019-05-22 15:10  菲菲一个  阅读(487)  评论(0编辑  收藏  举报