簡體   English   中英

帶注解@Autowired的Spring配置不起作用-逐步

[英]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為null。

基本內容已正確設置(如依賴項等),因為在測試應用程序的第一個版本中,我使用的是基於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不是spring托管的bean。 通過添加類似於UserService @Component使其春季管理。
  • 使用spring bean factory或應用程序上下文(例如ClasspathXMLApplicationContext )獲取DemoApplication而不是new運算符。

spring將如何知道它必須運行此DemoApplication。

您必須使用SpringJunit4ClassRunner來運行它,如下所示:

注釋您的DemoApplication,如下所示:

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

    @Autowired
    private UserService userService;

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

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM