Spring 开发简单项目实战

[此项目是用spring2.5开发,主要代码源于马老师的项目,但是其中有些冗余的代码大可不必看,只看关键的,而且其中都会有一些错误,已经经过了改正,代码可以正确运行]

1 需要的jar包:

 Spring.jar

 Commons-logger.jar

2 运行流程:

  读取 xml文件 --- >

  获取userService实例 --->

 userDao实例(因为配置文件中有userDao实例,可以通过两种方式(一个是set/get方法,另一个是 带参构造函数的方法)) -->

userDaoImpl 执行save()方法

主要配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  <bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl">
  </bean>
	
  <bean id="userService" class="com.bjsxt.service.UserService">
  	
  	<property name="userDAO" ref="u" />
  	<!-- 
  	 <constructor-arg>
  	 	<ref bean="u"/>
  	 </constructor-arg> -->
  </bean>
  
</beans>


 

 

2 运行项目实例

3 FAQ

ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

运行此句需要 spring.jar和commons-logger两个包的东西,如果没有commons-logger的包会报异常

java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory

缺少commons-logging-1.0.4.jar,版本越新越好

 

 4 项目渐进式变更

  1) 如果把

<bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl">

改成

<bean name="u" class="com.bjsxt.dao.impl.UserDAOImpl">

也是可以的

   2) 更改userDao的属性

<bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl">

  <bean name="userDAO" class="com.bjsxt.dao.impl.UserDAOImpl">
   <property name="daoId" value="8"></property>
   <property name="daoStatus" value="good"></property>
  </bean>

则可以获取userDao的初始化值

源码下载地址:

http://download.csdn.net/detail/jintianhen1/5686231

  3) 更改UserDao的属性为复杂的值,一样可以支持的 此示例是针对 userDao的

<bean name="userDAO" class="com.bjsxt.dao.impl.UserDAOImpl">
  	<property name="sets">
  		<set>
  			<value>1</value>
  			<value>2</value>
  		</set>
  	</property>
  	<property name="lists">
  		<list>
  			<value>1</value>
  			<value>2</value>
  			<value>3</value>
  		</list>
  	</property>
  	<property name="maps">
  		<map>
  			<entry key="1" value="1"></entry>
  			<entry key="2" value="2"></entry>
  			<entry key="3" value="3"></entry>
  			<entry key="4" value="4"></entry>
  		</map>
  	</property>
  </bean>


4)

在配置文件中使用autowire 此处针对 userService

  <bean id="userService" class="com.bjsxt.service.UserService" scope="prototype" autowire="byType">

 则 这个bean里面可以不在配置 property 或者构造方法两种的注释方式了

5) 初始化和销毁问题

(会发现后面的代码配置文件里写的越来越少)

在 UserService类里面写了 init 和 destroy方法

  <bean id="userService" class="com.bjsxt.service.UserService" init-method="init" destroy-method="destroy" scope="prototype">

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

静山晚风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值