Spring 带有注释@Autowired 的配置不起作用 - 逐步

Spring Configuration with annotations @Autowired not working - step by step

为了使用基于注解的配置,我已经执行了这些步骤:

a) beans.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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <context:annotation-config/>

    <context:component-scan base-package="test.*"/>

</beans>

b) 然后我有这个组件:

package test;
@Component
public class InMemoryUserService implements UserService 

c) 然后我尝试使用自动装配:

@Autowired
private UserService userService;

并且在运行时 userService 为空。

基本内容设置正确(如依赖项等),因为在测试应用程序的第一个版本中,我使用的是基于 xml 的配置,并且运行顺利。

这是一个使用自动装配的class:

public class DemoApplication {

    @Autowired
    private UserService userService;

    public DemoApplication() {
    }


    public static void main(String[] args) {

        DemoApplication da = new DemoApplication();
        da.userService.getUserByEmail("blabla@gmail.com");
    }
}

我还有什么遗漏的吗?

spring 如何知道它必须 运行 这个 DemoApplication。

您必须 运行 使用如下 SpringJunit4ClassRunner 内容:

如下所示注释您的 DemoApplication:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration
    public class DemoApplication {

    @Autowired
    private UserService userService;

    @Test
    public void testBean() {
     userService.getUserByEmail("");
    }

    }

那是因为-

  • DemoApplication 不是 spring 托管 bean。通过添加类似于 UserService.
  • @Component 使其成为 spring 管理
  • 使用 spring bean 工厂或应用程序上下文,例如 ClasspathXMLApplicationContext,以获取 DemoApplication 而不是 new 运算符。