maven搭建web項目和spring的IoC(Inversion of Control)

maven搭建web項目和spring的IoC(Inversion of Control)

一?? ??在IDEA 中使用maven創(chuàng)建web項目

第一種:創(chuàng)建一個空的maven項目(不勾選create from archetype),在/src/main下創(chuàng)建webapp包,webapp下創(chuàng)建WEB-INF包,WEB-INF下新建web.xml;再在pom.xml中寫<packaging>war</packaging>,將tomcat插件寫入(該tomcat與本地的tomcat無關(guān)),再將view中的maven打開,刷新,點擊tomcat????--->tomcat7:run

第二種:創(chuàng)建一個maven-archetype-webapp的maven項目;將tomcat插件寫入pom.xml;在Edit Configurations? ->+->maven,在Command line 行寫tomcat7:run

二????eclipse?maven創(chuàng)建web項目

新建maven project(勾選Create? a simple project) ->Group Id(包名) Artifact id(項目名) packing(可選擇類型:war) ->項目創(chuàng)建后會報錯(找不到web.xml) ->右擊項目,點擊JavaEE Tools->Generate Deployment...->刷新,建一個頁面->將相關(guān)插件添加到pom.xml中(項目會有小叉)->右擊項目->maven->update project->運行項目:右擊項目->Run:As->maven bulid(有兩個,第二個可以手動執(zhí)行命令tomcat7:run)

三? ? spring的IoC

1? ? spring

Spring框架主要由七部分組成,分別是 Spring Core、 Spring AOP、 Spring ORM、 Spring DAO、Spring Context、 Spring Web和 Spring Web MVC。

2????IoC

(1)????在pom.xml中添加spring-context依賴

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->

<dependency>

? ? <groupId>org.springframework</groupId>

? ? <artifactId>spring-context</artifactId>

? ? <version>5.2.1.RELEASE</version>

</dependency>

(2)????sts可以直接創(chuàng)建spring bean configuration file,eclipse不可以,需要手動編寫如下

(3)????spring容器默認生成的對象為singleton(單例模式,獲取的是同一個bean即為同一對象),? score="prototype"多例(Java項目兩個,web項目四個,多了request和session)

想通過id獲取bean,要有無參構(gòu)造<bean id="student1" class="com.qianfeng.Student"/>

(4)????無參構(gòu)造器和propertyerty對象賦值,必須要有標準的setter方法,因為property和JavaBean中的setter方法相關(guān)

<property name="sid" value="1"></property>

(5)????有參構(gòu)造對象賦值四種(幾個constructor-arg就會調(diào)用幾參構(gòu)造,沒有相應(yīng)就報錯):

1????通過name和value賦值????<constructor-arg name="sid" value="2"/>

2????按value的順序賦值:可能會出現(xiàn)類型轉(zhuǎn)換錯誤????<constructor-arg value="2"/>

3? ?相同類型按順序賦值,不同類型順序無要求????<constructor-arg type="int" value="2"/>

4????按"角標"位置賦值,從0開始????<constructor-arg index="0" value="2"/>

引用:給一個對象的屬性賦值????<constructor-arg type="BirthDays" ref="birth1"/>

(6)? ? p名稱空間注入

xmlns:p="http://www.springframework.org/schema/p"

上方是一個鏈接資源,前面p可變,后面p不可變,將這個加入就可用下方的格式

<bean id="student2" class="com.qianfeng.Student" p:sid="1" p:name="小紅" p:sex="true" p:score="90" p:birth-ref="birth2"></bean>

測試類:ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml")

ac.getBean("student5", Student.class);后面的Student.class可以不寫,但需要強轉(zhuǎn)類型

關(guān)閉ApplicationContext資源(不關(guān)會有警告)((ClassPathXmlApplicationContext)ac).close();

今天有兩個錯誤:

1.NoSuchMethodExcption:沒有無參構(gòu)造

2,NotWriteablePropertyExcption:不是一個可寫屬性;JavaBean中setter方法沒寫;或者在bean.xml中屬性名寫錯

2020-02-25在千峰線上學(xué)習(xí)的第12天,武漢加油

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容