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



我已经执行了以下步骤以使用基于注释的配置:

a) 豆类.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 的配置并且运行顺利。

这是一个使用自动连线的类:

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");
    }
}

我还缺少什么吗?

那是因为——

  • DemoApplication不是春豆。通过添加类似于UserService@Component来使其进行春季管理。
  • 使用 Spring Bean 工厂或应用程序上下文(例如 ClasspathXMLApplicationContext)来获取DemoApplication而不是new运算符。

春天怎么知道它必须运行这个演示应用程序。

您必须使用如下所示SpringJunit4ClassRunner运行它:

注释您的演示应用程序,如下所示:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration
    public class DemoApplication {
    @Autowired
    private UserService userService;
    @Test
    public void testBean() {
     userService.getUserByEmail("");
    }
    }

最新更新