2017-10-07 136 views
1

現在我非常困惑,我想在我的一個Controller類中使用@Autowired MongoClient屬性,但沒有成功。它的棘手部分是@Autowired正在從我的@RestController工作。Spring Boot - Autowired MongoClient

@RestController 
public final class WebController { 

    /** mongoClient */ 
    @Autowired 
    private MongoClient mongoClient; <- here it's working ... 
... 
} 

但:

@Controller 
public final class MongoUsersDAO { 

    /** mongoClient */ 
    @Autowired 
    private MongoClient mongoClient; <- not working ... 
... 
} 

在這裏我得到空。

我不認爲這個問題將是組件掃描,而我@SpringBootApplication位於XYZ,我在XYZT @RestController和我在xyzk包@Controller,因此他們的攤位應由Spring掃描。 (Eclipse也將我的@Controller標記爲Spring類)

那麼還有什麼問題呢?

注: 如果我添加這對我@Controller它的正常工作,但仍@Autowired工作wount:

@PostConstruct 
    public void init() { 
    System.out.println("INIT"); 
    } 

注:在提到MongoUsersDAO的自動裝配Autowired的事情是根本不工作,我我試圖從application.properties中獲得一個簡單的屬性,但沒有成功。

+0

奇怪。任何日誌?你叫什麼新的MongoUsersDAO()? 。奇怪爲什麼DAO類是用@Controller註釋的? – Barath

+0

我試着用服務,組件等對它進行註釋。新的請求發出時,新的mongoUsersDAO()在WebController中調用。 (這是一個測試實現) –

+0

這就是問題所在。不要調用新的mongoUserdDao()。如果你這樣做,自動裝配將不會發生。 – Barath

回答

1

您的問題發生是因爲您在WebController類中調用了new MongoUserDAO(),正如您在問題下方的註釋中提到的那樣。如果您手動實例化對象並且您的字段使用@Autowired進行了註釋,則該字段將不會使用預期的實例進行實例化。

MongoUsersDAO直接注入您的WebController類,如下圖所示,Spring將爲您注入MongoClientMongoUserDAO類。

WebController

@RestController 
public final class WebController { 

    /** Service/Repository class*/ 
    @Autowired 
    private MongoUsersDAO dao; 

    @GetMapping("/all") 
    public String getAll(){ 
     dao.callSomeMethod(); 
    } 
} 

MongoUsersDAO

@Repository 
public final class MongoUsersDAO { 

    /** mongoClient */ 
    @Autowired 
    private MongoClient mongoClient; 
... 
} 
+0

再次謝謝:) –