没有xml bean定义的Spring组件检测

wad*_*rld 2 spring annotations javabeans

@Component只要配置了上下文组件扫描,只使用注释就能创建spring bean是否正确?

使用带有Java 6的spring 3.0.5.

我的测试用例是:

@ContextConfiguration(locations={"classpath:spring-bean.xml"})

public class ServerServiceUnitTest extends AbstractJUnit4SpringContextTests {
    @Autowired
    private ServerService serverService;

    @Test
    public void test_server_service() throws Exception {
           serverService.doSomething();
           //additional test code here
        }
}
Run Code Online (Sandbox Code Playgroud)

spring-bean.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/>
</beans>
Run Code Online (Sandbox Code Playgroud)

我想成为一个bean的课程是:

@Component("ServerService")
public class ServerServiceImpl implements ServerService {
    private static final String SERVER_NAME = "test.nowhere.com";
        //method definitions.....'
}
Run Code Online (Sandbox Code Playgroud)

那不足以让spring实例化ServerServicebean并进行自动装配吗?

我得到的错误是:

由以下原因引起:org.springframework.beans.factory.NoSuchBeanDefinitionException:没有为依赖项找到类型[serversystem.ServerService]的匹配bean:期望至少有1个bean符合此依赖项的autowire候选者.依赖注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}

我确定我错过了一些简单的事情.

nic*_*ild 6

你有没有在你的定义spring-beans.xml<context:component-scan>元素:

<context:component-scan base-package="the.package.with.your.service"/>
Run Code Online (Sandbox Code Playgroud)

包含

<context:annotation-config/>
Run Code Online (Sandbox Code Playgroud)

只允许你使用@Required,@Autowired以及@Inject用于配置的注解.通过指定<context:component-scan>,您将告诉Spring在哪里查找@Component注释.