當開發springboot項目時,與springmvc項目對比 pom配置中的各種版本 會使人疑惑,還有springboot bean的注入方式也有多種。
版本
用mongodb對版本進行解釋
比較下面三個maven pom依賴
1、spring-boot-starter-data-mongodb --- springboot
2、spring-data-mongodb --- spring
3、mongo-java-driver --- 普通java包
上面三種方式都可以實現maven引用mongodb驅動 jar包。
1的特點是不需要寫版本號,寫了反而可能版本衝突報錯,版本號會根據springboot的版本自動生成合適的版本。
2 如果在spring boot項目中也不用寫版本號,版本號會根據spring自動生成一個適合的版本,而spring又會根據spring boot自動生成合適的版本,
而如果在spring項目中則要自己根據spring版本去判斷改用什麼版本號。
3則必須寫版本號,版本號可以隨意寫。
其中springboot的版本最新版是2.x,springboot 1x自身 和 2x自身相差不大,但是1x和2x相差很大。很多1x的項目不要輕易升級2x,但是在1x自身的各個版本之間可以升級。
springboot 1x 會自動生成 spring的 3x 版本號
所以在springboot項目中有spring-boot
springframework
等標識的依賴都不用寫版本號,而如果自己引用的比如fastjson等jar包則需要註明版本號
注入bean
在沒有spring的時候,創建java對象使用Bean bean = new Bean();
在有spring的時候,我們用@Autowired private Bean bean
自動注入對象
springboot在注入上也沒區別,有區別的是在bean的聲明上,如果不先聲明bean,直接用註解注入會報空指針錯誤。
spring 我們用.xml文件聲明,和註解聲明
springboot 我們用XXXConfig.java 配置類聲明和註解聲明,然後在application中配置掃描範圍,或者默認掃描當前文件下級的全部包
兩者都可以用註解聲明bean,比如 @Component(所有類都可以,不規範)@service(聲明服務,規範) @Repository(聲明DAO,規範)等
mongodb
mongodb有2x和3x,數據庫這裏對我們代碼影響不大,但是驅動也有2x和3x
這兩套版本的區別就非常大了,2x項目直接升級到3x,會導致
- 部分代碼報錯
- 配置文件報錯
先寫application.properties配置文件,然後
其中2x的配置,主要是mongo
<mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />
<bean id="userCredentials" class="org.springframework.data.authentication.UserCredentials">-->
<constructor-arg name="username" value="${mongo.username}"/>
<constructor-arg name="password" value="${mongo.password}"/>
// 此處爲用戶名和密碼,默認爲空
</bean>
3x的配置,主要是mongo-client,並且3x不支持 無密碼的認證
<mongo:mongo-client id="mongoClient" host="${mongo.host}" port="${mongo.port}" credentials="${mongo.username}:${mongo.password}@${mongo.dbname}">
<mongo:client-options
connections-per-host="${mongo.connectionsPerHost}"
min-connections-per-host="${mongo.minConnectionsPerHost}"
threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
connect-timeout="${mongo.connectTimeout}"
/>
</mongo:mongo-client>
<mongo:db-factory id="mongoDbFactory"
dbname="${mongo.dbname}"
mongo-ref="mongoClient"/>
<mongo:template id="mongoTemplate" db-factory-ref="mongoDbFactory" write-concern="NORMAL"/>
最後都是通過
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
protected MongoOperations mongoTemplate = (MongoOperations) ctx.getBean("mongoTemplate");
方式獲取bean。
如果我們使用springboot,XXXConfig.java文件的方式聲明bean,就固定使用
spring.data.mongodb.uri=mongodb://name:[email protected]:port/database?maxPoolSize=256
這種配置寫到application.properties文件裏,
然後再配置類中可以return bean,或者不做配置類,直接注入mongoTemplet就可以
@Autowired
MongoTemplate mongoTemplate