开发者

Spring component detection without xml bean definitions

开发者 https://www.devze.com 2023-03-05 19:40 出处:网络
Is it correct that one can create spring beans using just the @Component annotation as long as context component scanning is configured?

Is it correct that one can create spring beans using just the @Component annotation as long as context component scanning is configured?

Using spring 3.0.5 with Java 6.

My test case is:

@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
        }
}

The spring-bean.xml file contains:

<?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>

My class I want to be a bean is:

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

Should that not be sufficient for spring to instantiate the ServerService bean and do the autowiring?

The error I get is:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [serversystem.ServerService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

I'm sure I'm missing something simple.


You have not defined in your spring-beans.xml the <context:component-scan> element:

<context:component-scan base-package="the.package.with.your.service"/>

The inclusion of

<context:annotation-config/>

only allows you to use @Required, @Autowired, and @Inject annotations for configuration. By specifying the <context:component-scan>, you are telling Spring where to look for @Component annotations.


if you are using annotated controllers and other features you should include

<mvc:annotation-driven/>

you should use

<context:component-scan base-package="spring3.example.controllers"/>

to specify the package in which controller classes are stored.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号