spring获取不到bean

今天在做spring单元测试的时候,有一个bean死活加载不到。

错误:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'userService' is defined
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:694)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1168)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:281)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
	at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
	at com.spring_test.UserManagerTest.before(UserManagerTest.java:14)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)


在丁未的过程中,发现原来是因为在spring的配置中缺少了:
<context:component-scan base-package="com.spring_test"/>
导致加载不到userService这个bean。

测试代码如下:
userService:
public interface UserService {

	public User getUserById(String userId);
}


UserServiceImpl
import org.springframework.stereotype.Service;

@Service("userService")
public class UserServiceImpl implements UserService{

	public User getUserById(String userId) {
		return null;
	}

}

测试类:
public class UserManagerTest {
	private UserService userService;
	@Before
	public void before()
	{
		ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"/spring/spring-config.xml"});
		userService = (UserService) ac.getBean("userService");
	}
	
	@Test
	public void testUser()
	{
		String userId ="001";
		userService.getUserById(userId);
	}

}


spring-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">


<context:annotation-config/>    
<context:component-scan base-package="com.spring_test"/>

    <!-- 引入dbconfig.properties属性文件 -->
    <context:property-placeholder location="classpath:dbconfig.properties" />
    <!-- 自动扫描(自动注入),扫描me.gacl.service这个包以及它的子包的所有使用@Service注解标注的类 -->
    <context:component-scan base-package="me.gacl.service" />
</beans>

你可能感兴趣的:(spring)