xml封装数据,使用xsl将数据装饰成各种不同的展现形式,xsl可以通过xPath操作xml文件。
一,控制反转与依赖注入
由容器来管理对象之间的依赖关系,就叫“控制反转”或“依赖注入”
二,spring组件安装
1,spring_home/dist/spring.jar
2,spring_home/lib/jakarta-commons/commons-logging.jar
3,spring_home/lib/log4j/log4j-1.2.4.jar
spring的配置文件是\spring-framework-2.0.8\samples\jpetstore\war\WEB-INF/applicationContext.xml拷贝到src下,同时把log4j.properties也拷贝到src目录下。
ioc容器管理对象和对象间的依赖关系
spring IOC容器的关键点:
必须将被管理的对象定义到spring配置文件中,必须定义构造函数或setter方法,让spring将对象注入过来
ioc实现是di依赖注入,ioc就是将变化的对象创建并装备好
三,实例
建立数据层:com.jzq.spring.dao
UserDao类:
package com.jzq.spring.dao;
public class UserDao {
public void save(String username,String password){};}UserDao4MySqlImpl类:
package com.jzq.spring.dao;
public class UserDao4MySqlImpl extends UserDao {
@Override public void save(String username, String password) { System.out.println("MySql实现"); }}UserDao4OracleImpl类:
package com.jzq.spring.dao;
public class UserDao4OracleImpl extends UserDao{
@Override public void save(String username, String password) { System.out.println("Oracle实现"); }}建立数据管理层:com.jzq.spring.manager
UserManager类:
package com.jzq.spring.manager;
public class UserManager {
public void save(String username,String password) { }}UserManagerImpl类:
package com.jzq.spring.manager;
import com.jzq.spring.dao.UserDao;
public class UserManagerImpl extends UserManager {
private UserDao userDao; //构造方法// public UserManagerImpl(UserDao userDao)// { // this.userDao=userDao;// } //提供的set方法 public void setUserDao(UserDao userDao) { this.userDao=userDao; } public void save(String username,String password) { this.userDao.save(username, password); }}建立客户端:com.jzq.spring.client
package com.jzq.spring.client;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;import com.jzq.spring.dao.UserDao4OracleImpl;
import com.jzq.spring.manager.UserManager;import com.jzq.spring.manager.UserManagerImpl;public class Client {
public static void main(String[] args) {//普通的调用代码
// UserManager userManager=new UserManagerImpl(new UserDao4OracleImpl());// userManager.save("张三", "123");//使用spring的ioc容器注入调用
BeanFactory factory=new ClassPathXmlApplicationContext("applicationContext.xml"); //得到userManager对象并且实例化依赖的对象,并实现依赖的注入 UserManager userManager=(UserManager)factory.getBean("userManager"); userManager.save("张三", "123"); }}spring配置文件的注入:
<beans xmlns=""
xmlns:xsi="" xmlns:aop="" xmlns:tx="" xsi:schemaLocation=" "><bean id="userDao4MySqlImpl" class="com.jzq.spring.dao.UserDao4MySqlImpl"/>
<bean id="userDao4OracleImpl" class="com.jzq.spring.dao.UserDao4OracleImpl"></bean> <bean id="userManager" class="com.jzq.spring.manager.UserManagerImpl"> <!-- 构造方法注入 <constructor-arg ref="userDao4MySqlImpl"/> --> <!-- set注入方法 --> <property name="userDao" ref="userDao4OracleImpl"/> </bean> </beans>