2017-02-18 61 views
0

春季文檔說,目前接口DI是不可能的。看到這裏:http://www.springbyexample.org/examples/core-concepts-dependency-injection-to-the-rescue.htmlSpring Boot,DI可能使用接口,但在Spring中不可行?

我剛開始使用Spring引導,我做了一個簡單的web應用程序,我用DI使用接口。我無法在網上找到原因。爲什麼Spring Boot在Spring中沒有這個功能!

請幫我理解這個概念。

感謝。

編輯

道Imple。

@Repository 
public class AbcDaoImpl implements AbcDaoInt{ 
    @Autowired 
    JdbcTemplate jdbc; 

    @Override 
    public int selectABC(String user, String password){ 
     // some db query 
    } 

DAO接口

@Component 
public interface AbcDaoInt{ 
    int selectABC(String user, String password);  
} 

服務

@Service 
public class adapter { 
    @Autowired 
    AbcDaoInt abcDao; 

    public Map<String, Object> abc(String user, String password) { 

    try{ 
      int abcId = abcDao.selectABC(user, pwd); 
     } 
    } 
+0

您鏈接的頁面已過時,只是部分正確,完全沒有定義「接口注入」的含義。你也不是這麼說。 Spring Boot使用Spring進行依賴注入,所以問題是沒有意義的。 –

+0

@RishiPandey你能告訴我們一些代碼嗎?你不能做接口注入,因爲你需要一些具體的實現。也許你很迷惑讓我們說@ Autowire接口接口,其中接口是一個接口,但春天將自動裝載它的具體實現 – pezetem

+0

@JBNizet我想從鏈接頁面指出,Spring目前有setter和構造函數依賴注入。而且我知道Spring引導爲DI使用了Spring。可能是我不理解這個概念,但我的問題是有效的。 – RishiPandey

回答

1

有春春啓動關於DI之間沒有什麼區別。 可以爲字段使用接口並將實現注入到該字段中。

我不明白的鏈接頁面是指

接口注入什麼 - 這不是在Spring中實現目前

似乎到b錯落後的。

+0

@Stefen感謝您的回覆。所以你的意思是說在Spring中可以使用接口注入? – RishiPandey

+0

@RishiPandey再次,直到我們有一個「接口注入」的定義,我們不能回答這個問題。你是否有一個? –

+0

我們無法在Spring mvc中將dao接口定義爲bean,Spring需要impl。類。但在我上傳編輯部分的代碼(Spring Boot)中:我使用interfaceDao(abdDao)對象。而如果我在Spring MVC中嘗試相同的話,那麼我將在運行時得到錯誤,說明Spring需要實現類....? – RishiPandey

1

你究竟要做什麼注射接口。不是接口應該由java類實現,所以無論何時注入接口,都意味着應該注入一些實現接口的類。

這是你應該怎麼做的,你必須在這些類存在的包上啓用組件掃描,然後啓用註釋以便使用註釋。

<context:component-scan base-package="" /> 
<mvc:annotation-driven> 


public interface singleInterface{ 
    void someMethod(); 
} 

@Component(value="b") 
class B implements singleInterface{ 
    public void someMethod(){ 
    System.out.println(「from b class」); 
    } 
} 

@Component(value=「a」) 
class A implements singleInterface{ 
    public void someMethod(){ 
    System.out.println(「from A class」); 
    } 
} 

//injecting 

@Autowire 
@Qualifier("b") 
singleInterface bInterface; 

bInterface.someMethod();//print from b class. 

@Autowire 
@Qualifier("a") 
singleInterface aInterface; 

aInterface.someMethod();//print from a class. 

這個工程上和spring mvc你沒有在春季啓動,使component scan

+0

我的代碼也正常工作。我的問題是爲什麼Spring Boot允許接口DI。而文檔說春天不允許接口DI。 – RishiPandey

+0

上面的帖子是用spring編碼的,爲什麼你說那不允許? – Priyamal

+0

這正是我想知道的。 我們無法在Spring mvc中將dao接口定義爲bean,Spring需要impl。類。但我發佈在我的問題的編輯部分的代碼是使用Spring Boot,我們不需要指定xml配置。和豆類 – RishiPandey

相關問題