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

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

一     在IDEA 中使用maven创建web项目

第一种:创建一个空的maven项目(不勾选create from archetype),在/src/main下创建webapp包,webapp下创建WEB-INF包,WEB-INF下新建web.xml;再在pom.xml中写<packaging>war</packaging>,将tomcat插件写入(该tomcat与本地的tomcat无关),再将view中的maven打开,刷新,点击tomcat    --->tomcat7:run

第二种:创建一个maven-archetype-webapp的maven项目;将tomcat插件写入pom.xml;在Edit Configurations  ->+->maven,在Command line 行写tomcat7:run

二    eclipse maven创建web项目

新建maven project(勾选Create  a simple project) ->Group Id(包名) Artifact id(项目名) packing(可选择类型:war) ->项目创建后会报错(找不到web.xml) ->右击项目,点击JavaEE Tools->Generate Deployment...->刷新,建一个页面->将相关插件添加到pom.xml中(项目会有小叉)->右击项目->maven->update project->运行项目:右击项目->Run:As->maven bulid(有两个,第二个可以手动执行命令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可以直接创建spring bean configuration file,eclipse不可以,需要手动编写如下

(3)    spring容器默认生成的对象为singleton(单例模式,获取的是同一个bean即为同一对象),  score="prototype"多例(Java项目两个,web项目四个,多了request和session)

想通过id获取bean,要有无参构造<bean id="student1" class="com.qianfeng.Student"/>

(4)    无参构造器和propertyerty对象赋值,必须要有标准的setter方法,因为property和JavaBean中的setter方法相关

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

(5)    有参构造对象赋值四种(几个constructor-arg就会调用几参构造,没有相应就报错):

1    通过name和value赋值    <constructor-arg name="sid" value="2"/>

2    按value的顺序赋值:可能会出现类型转换错误    <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可以不写,但需要强转类型

关闭ApplicationContext资源(不关会有警告)((ClassPathXmlApplicationContext)ac).close();

今天有两个错误:

1.NoSuchMethodExcption:没有无参构造

2,NotWriteablePropertyExcption:不是一个可写属性;JavaBean中setter方法没写;或者在bean.xml中属性名写错

2020-02-25在千峰线上学习的第12天,武汉加油

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。