JavaWeb项目中引入spring框架
2024-08-30 03:55:08
主要步骤有以下3步:
1:下载spring的jar包
2:在项目中web.xml中添加spring配置
3:bean配置文件-applicationContext.xml
1:引入包,这个就不说了,官网下载。
spring-core-3.2.3.RELEASE.jar 核心依赖jar包
spring-context-3.2.3.RELEASE.jar 容器包
spring-beans-3.2.3.RELEASE.jar beans的管理包
spring-expression-3.2.3.RELEASE.jar
另外还需加入commons-logging.jar
2:在web.xml中添加spring配置。一个监听,一个路径(配置bean文件所在目录)
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 默认配置在WEB-INF目录下 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/applicationContext.xml</param-value> <!-- <param-value>/WEB-INF/spring*.xml</param-value> -->
</context-param>
3:bean配置文件applicationContext.xml
<beans>
<!-- 每个bean都对应有一个id和class -->
<bean id="u" class="dao.UserDaoImpl"></bean>
<!-- 下面代码表示:在id为userService的service中有一个名叫userDao的属性,
更准确的说是在service中有一个setUserDao的方法 ,该方法调用时必须把上面id为u的bean传进来,
此时就把这两个东西装配起来:专业说法是动态装配。
即可以把UserService.java中的private的userDao属性给注入进来【注入】
<!-- 一定要注意:下面代码中的property中的name的值必须和你UserService.java中定义的变量要一致。
也就是和必须和你service中的setDao的方法匹配,有setDao(),则name的值就是dao,即去掉前面的set -->
-->
<bean id="userService" class="service.UserService">
<property name="dao" ref="u"></property>
</bean> </beans>
4:使用(UserService.java)
ApplciationContext ctx=new ClasspathXmlApplicationContext(“beans.xml”);
//UserService service =new UserService();
//UserDao userDao=(UserDao)factory.getBean("u");
/**
* u已经配置在xml中,直接从配置文件中拿,这是spring一个重要的功能
* 此时,思考能不能userservice也不要我们new而是直接从配置文件中拿:如果直接在xml中加bean然后从factory中拿,
* 此时会报错,提示userdao没有初始化。
* 此时spring另一个重要功能就用到了:可以直接在配置文件中将dao和service的关联关系设定好(见配置文件:上一步)
*/
UserService service =(UserService)ctx.getBean("userService");
User u =new User();
service.add(u);
最新文章
- 模拟下载的进度条ProgressBar
- Hbase安装配置(靠谱亲测)
- ARP协议工作流程
- C#操作Excel(2)-- 打开-读取Excel文档
- js实现ppt
- 照猫画虎学gnuplot之简单介绍
- 大写String和小写string的区别
- Ajax基础知识(二)
- Mysql 使用CMD 登陆
- 用scala实现一个基于TCP Socket的快速文件传输程序
- Android之View绘制流程开胃菜---setContentView(...)详细分析
- Snapshot Types
- MySQL 数据库规范--调优篇(终结篇)
- <;记录>; axios 模拟表单提交数据
- 自学Linux Shell19.1-gawk程序基础特性
- python实用库:PrettyTable 学习
- 数据库查询实例(包含所有where条件例子)
- python-下载百度图片到本地
- JAVA输入随笔
- Coursera: Internet History, Technology, and Security