搜索
您的当前位置:首页正文

spring初试

来源:知库网
1.新建项目:file→New→Project…→WebProject→Next→ProjectName:spring(项目名)→选中JavaEE5.0→Finish(新建项目完成)2.加入spring架包,三个主要jar包

1)Spring2.5.6\\software\\spring-framework-2.5.6-with-dependencies\\spring-framework-2.5.6\\dist路劲下的:spring.jar

2)Spring2.5.6\\software\\spring-framework-2.5.6-with-dependencies\\spring-framework-2.5.6\\lib\\jakarta-commons路径下的:commons-logging.jar

3)Spring2.5.6\\software\\spring-framework-2.5.6-with-dependencies\\spring-framework-2.5.6\\lib\\log4j路径下的:log4j-1.2.15.jar一个配置文件:

Spring2.5.6\\software\\spring-framework-2.5.6-with-dependencies\\spring-framework-2.5.6\\samples\\jpetstore\\war\\WEB-INF路径下的:applicationContext.xml其他类库增加spring依赖库,*SPRING_HOME/dist/spring.jar*SPRING_HOME/lib/jakarta-commons/commons-logging.jar*SPRING_HOME/lib/log4j/log4j-1.2.15.jar如果使用了切面编程,还需下列jar文件:lib\\aspectj\\aspectjweaver.jar和aspectjrt.jarlib\\cglib\\cglib-nodep-2.1.3.jar如果使用了jsr-250中的注解,还需要下列jar文件:lib\\j2ee\\common-annotations.jar3.配置applicationContext.xml\"contextConfigLocation\").4.初始化applicationContext.xml

在servlet中,写上如下代码,加载applicationContext.xml配置文件//初始化springApplicationContextapplicationContext=new//获得UserBo实例UserBouserBo=(UserBo)applicationContext.getBean(\"userBo\");ClassPathXmlApplicationContext(\"applicationContext.xml\");异常1:

分析:

还没有把spring的配置文件\"applicationContext.xml\"加载到项目中所以没有读到配置文件没读到配置文件,就没有类的注入,输入保空指针异常解决:

在servlet中加上下面两句//初始化springApplicationContextapplicationContext=newClassPathXmlApplicationContext(\"applicationContext.xml\");//获得UserBo实例UserBouserBo=(UserBo)applicationContext.getBean(\"userBo\");异常2:

Errorcreatingbeanwithname'userBo'definedinclasspathresource[applicationContext.xml]:Cannotresolvereferencetobean'userDao'whileorg.springframework.beans.factory.NoSuchBeanDefinitionException:beannamed'userDao'isdefinedsettingconstructorargument;nestedexceptionisNo错误创建名为'userBo在类路径资源定义[applicationContext.xml中]豆:无法解析引用豆UserDAO的',而设置构造函数的参数;嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:名为'UserDAO的无豆'的定义分析:

userBo无法引用UserDAO;注:跟userBo类中的变量,没有关系解决:

把userDao改为UserDao异常3:

Errorcreatingbeanwithname'UserBo'definedinclasspathresource[applicationContext.xml]:1constructorargumentsspecifiedbutnomatchingconstructorfoundinbean'UserBo'(hint:specifyindexand/ortypeargumentsforsimpleparameterstoavoidtypeambiguities)错误创建bean的名称为'UserBo在类路径资源定义[applicationContext.xml中]:1构造函数的参数指定但没有匹配的构造函数,豆UserBo'(提示发现:指定索引和/或简单的参数类型的类型参数,以避免歧义)

分析:

UserBo没有构造函数解决:

异常4

Nobeannamed'userBo'isdefined命名为'userBo'没有定义的bean分析:

跟配置文件不一致解决:

UserBo改为userBo

因篇幅问题不能全部显示,请点此查看更多更全内容

Top