spring boot新增mongo-java驅動包之後報錯的原因

fusugongzi發表於2017-07-18

由於在spring boot專案中需要連線公司伺服器的mongo資料庫,所以在pom檔案中引入mongo-java的驅動包

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.4.2</version>
</dependency>


但是發現在啟動專案的過程中,無論是否用到了這個包,都會包如下的exception:

com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.connection.SocketStream.open(SocketStream.java:63)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:113)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:57)
at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
... 3 common frames omitted





後來經過上網查資料發現是由於spring boot預設載入了對於mongo的支援,在專案啟動的過程中會預設的連線本地的mongo,而我本地並沒有mongo資料庫,所以導致報錯。

解決方案:移除spring  boot預設的對於mongo的支援,在啟動類的註解之上加上註解將mongo支援移除即可。


@EnableAutoConfiguration(exclude={MongoAutoConfiguration.class})

相關文章