Spring IoC
Spring
一个开源的应用程序框架,一个一站式的框架。
1.IoC容器
2.AOP实现
3.数据访问支持:简化hibernate编码,声明式事物
4.Web集成
一般代指Spring Framework。
Spring Framework
Spring提供了表现层(mvc)到业务层(Spring)再到数据层(data)的全套解决方案,基于Spring,你可以方便的与其他框架进行集成,如hibernate
,ibatis,structs
等,Spring官方的原则是绝不重复造轮子,有好的解决方案只需要通过Spring进行集成即可。Spring Framework 本身并未提供太多具体的功能,它主要专注于让你的项目代码组织更加优雅,使其具有极好的灵活性和扩展性,同时又能通过Spring集成业界优秀的解决方案
Inversion of Control(控制反转/Dependency Inversion Principle):
1.一个重要的面向对象编程的法则来削减计算机程序的耦合问题
2.轻量级的Spring框架的核心
IoC负责什么?
- 创建对象
- 管理对象(通过依赖注入DI)
- 装配对象
- 配置对象
- 管理对象生命周期
实现技术:
1.Java反射技术实现
2.配置文件组装对象
将组件对象的控制权从代码本身转移到外部容器
1.组件化思想:分离关注点,接口和实现分离
2.依赖的注入:将组件的构建和使用分开
Ioc最重要的2个类是什么?
- BeanFactory
- bean的定义
- 读取bean配置文档
- 管理bean加载、实例化
- 控制bean的生命周期
- 维护bean之间的依赖
- ApplicationContext,这是BeanFactory的子接口
- 支持国际化
- 统一的资源文件访问方式
- 提供在监听器中注册bean事件
- 同时加载多个配置文件
- 载入多个上下文
范例:
1.HelloSpring类
package com.Elastic.SpringDemo1.ivy.demo; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class HelloSpring { private String meg; public String getMeg() { return meg; } public void setMeg(String meg) { this.meg = meg; } public void sayHello() { System.out.println("Hello," + meg); } public static void main(String[] args) { /*//1.创建对象 HelloSpring hs = new HelloSpring(); //2.給对象赋值 hs.setMeg("Spring !!!"); //3.调用对象的方法 hs.sayHello();*/ //使用Spring完成上面的操作 //1.创建Spring IoC容器 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //2.通过容器获得对象 HelloSpring hs = (HelloSpring) context.getBean("helloSpring"); //3.调用对象的方法 hs.sayHello(); } }
2.applicationContext.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans.xsd"> 6 7 <!-- 由Spring的IoC容器创建对象 --> 8 <bean id="helloSpring" class="com.Elastic.SpringDemo1.ivy.demo.HelloSpring"> 9 <!-- 給属性赋值 --> 10 <property name="meg" value="Spring IoC"></property> 11 </bean> 12 13 </beans>
依赖注入--组件之间以配置文件的形式组织在一起,而不是以编码的方式耦合在一起
1.设值注入 -- 属性的setter访问器
可以使用p命名空间注入属性值
2.构造注入 -- 带参构造方法
1).技巧:编写带参构造方法,为保证使用的灵活性,建议添加无参构造方法
2).在Spring配置文件中通过<constructor-arg>元素为构造方法传参
a.、一个<constructor-arg>元素表示构造方法的一个参数,且使用时不区分顺序。
b.通过<constructor-arg>元素的index 属性可以指定该参数的位置索引,位置从0 开始。
c.<constructor-arg>元素还提供了type 属性用来指定参数的类型,避免字符串和基本数据类型的混淆。
p命名空间:使用属性而不是子元素的形式配置Bean的属性
1.引入p命名空间 xmlns:p="http://www.springframework.org/schema/p"
2.对于直接量(基本数据类型、字符串)属性:p:属性名="属性值"
对于引用Bean的属性:p:属性名-ref="Bean的id"
注入不同数据类型
1.注入直接量 使用<value>标签;特殊字符的处理
2.引用Bean 使用<ref>标签;注意bean属性和local属性的区别
3.使用内部Bean <property><bean>...</bean></property>
4.注入集合类型的属性 <list>\<set>\<map>\<props>标签
5.注入null和空字符串值 使用<null>注入null值;使用<value>注入空字符串值
范例: 打印机
1.定义墨盒和纸张的接口标准
a.Ink接口
1 package com.Elastic.SpringDemo1.ivy.printer; 2 3 /** 4 * 墨盒接口(墨盒规格) 5 * 6 */ 7 public interface Ink { 8 String getColor(); 9 }
b.Paper接口
1 package com.Elastic.SpringDemo1.ivy.printer; 2 3 /** 4 * 纸张接口(纸张的规格) 5 * 6 */ 7 public interface Paper { 8 void putChar(char c); 9 }
2.墨盒和纸张的接口的实现类
a.BlackInk类
1 package com.Elastic.SpringDemo1.ivy.printer; 2 3 public class BlackInk implements Ink{ 4 5 @Override 6 public String getColor() { 7 return "黑色"; 8 } 9 10 }
b.A4Paper类
1 package com.Elastic.SpringDemo1.ivy.printer; 2 3 public class A4Paper implements Paper{ 4 5 @Override 6 public void putChar(char c) { 7 8 System.out.print(c); 9 } 10 11 }
3.Printer类 -- 组装打印机
1 package com.Elastic.SpringDemo1.ivy.printer; 2 3 /** 4 * 打印机 5 * 6 */ 7 public class Printer { 8 Ink ink; 9 10 Paper paper; 11 12 //属性增加setter方法 13 public void setInk(Ink ink) { 14 this.ink = ink; 15 } 16 17 public void setPaper(Paper paper) { 18 this.paper = paper; 19 } 20 21 public void print(String content) { 22 System.out.println("打印机正在打印:"); 23 System.out.println("使用颜色:" + ink.getColor()); 24 for (int i = 0; i < content.length(); i++) { 25 paper.putChar(content.charAt(i)); 26 } 27 28 System.out.println("打印完毕......"); 29 } 30 31 }
4.printerContext.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans.xsd"> 6 7 <!-- 由Spring的IoC容器创建对象 --> 8 <bean id="blackPrinter" class="com.Elastic.SpringDemo1.ivy.printer.Printer"> 9 <!-- 給属性赋值(组装) --> 10 <property name="ink" ref="blackInk"></property> 11 <property name="paper" ref="A4"></property> 12 </bean> 13 14 <bean id="blackInk" class="com.Elastic.SpringDemo1.ivy.printer.BlackInk"></bean> 15 16 <bean id="A4" class="com.Elastic.SpringDemo1.ivy.printer.A4Paper"></bean> 17 18 </beans>
5.Test类 -- 运行打印机
1 package com.Elastic.SpringDemo1.ivy.test; 2 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6 import com.Elastic.SpringDemo1.ivy.printer.Printer; 7 8 public class Test { 9 10 public static void main(String[] args) { 11 //找到卖打印机的商店 12 //由Spring创建printer对象,并根据配置文件注入依赖的组件,完成组装 13 ApplicationContext context = new ClassPathXmlApplicationContext("printerContext.xml"); 14 //給老板说来一台打印机 15 Printer printer = (Printer) context.getBean("blackPrinter"); 16 printer.print("测试内容"); 17 } 18 19 }
范例:
1.实体类及其配置文件
a.User类
1 package com.Elastic.SpringDemo1.ivy.entity; 2 3 import java.io.Serializable; 4 5 public class User implements Serializable{ 6 private String loginName; 7 private String loginPass; 8 9 public String getLoginName() { 10 return loginName; 11 } 12 public void setLoginName(String loginName) { 13 this.loginName = loginName; 14 } 15 public String getLoginPass() { 16 return loginPass; 17 } 18 public void setLoginPass(String loginPass) { 19 this.loginPass = loginPass; 20 } 21 }
b.User.hbm.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 4 <hibernate-mapping> 5 <class name="com.Elastic.SpringDemo1.ivy.entity.User" table="user"> 6 <id name="loginName" type="java.lang.String"> 7 <column name="userName"></column> 8 <generator class="assigned"></generator> 9 </id> 10 <property name="loginPass" type="java.lang.String"> 11 <column name="passWord"></column> 12 </property> 13 </class> 14 </hibernate-mapping>
2.hibernate.cfg.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <!DOCTYPE hibernate-configuration PUBLIC 4 "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 5 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 6 7 <hibernate-configuration> 8 <session-factory> 9 <!-- 1.数据库连接信息 --> 10 <property name="connection.url">jdbc:mysql://localhost/hibernatedb</property> 11 <property name="connection.username">root</property> 12 <property name="connection.password">root</property> 13 <property name="connection.driver_class">com.mysql.jdbc.Driver</property> 14 <property name="dialect">org.hibernate.dialect.MySQLDialect</property> 15 <property name="show_sql">true</property> 16 <property name="format_sql">true</property> 17 18 19 <!-- 2.使用c3p0连接池 --> 20 <property name="hibernate.connection.datasource">com.mchange.v2.c3p0.ComboPooledDataSource</property> 21 <property name="c3p0.max_size">100</property> 22 <property name="c3p0.min_size">10</property> 23 <property name="c3p0.acquire_increment">5</property> 24 <property name="c3p0.idle_test_period">60</property> 25 <property name="c3p0.timeout">10</property> 26 27 <!-- 3.数据库对应的实体类的映射文件路径 --> 28 <mapping resource="com/Elastic/SpringDemo1/ivy/entity/User.hbm.xml"></mapping> 29 </session-factory> 30 </hibernate-configuration>
3.HibernateUtil类
1 package com.Elastic.SpringDemo1.ivy.util; 2 3 import org.hibernate.Session; 4 import org.hibernate.SessionFactory; 5 import org.hibernate.cfg.Configuration; 6 public final class HibernateUtil { 7 private static Configuration cfg = null; 8 private static SessionFactory sessionFactory = null; 9 10 //本地线程 11 public static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); 12 13 static{ 14 cfg = new Configuration().configure(); 15 sessionFactory = cfg.buildSessionFactory(); 16 } 17 18 public static Session getSession(){ 19 Session session = threadLocal.get(); 20 if (null == session || !session.isOpen()) { 21 session = sessionFactory.openSession(); 22 threadLocal.set(session); 23 } 24 return session; 25 } 26 }
4.dao包
a.IBaseDao接口
1 package com.Elastic.SpringDemo1.ivy.dao; 2 3 import java.io.Serializable; 4 import java.util.List; 5 import java.util.Map; 6 7 import org.hibernate.Session; 8 import org.hibernate.criterion.DetachedCriteria; 9 public interface IBaseDao<T> { 10 /** 11 * 12 * <p> 13 * <h3>方法功能描述:获取Session对象</h3> 14 * </p> 15 * @return 16 * @procedure 执行过程 17 * @see IBaseDao 18 */ 19 Session getSession(); 20 21 /** 22 * 23 * <p> 24 * <h3>方法功能描述:保存数据</h3> 25 * </p> 26 * @param record 需要保存的对象 27 * @procedure 执行过程 28 * @see IBaseDao 29 */ 30 void save(T record); 31 32 /** 33 * 34 * <p> 35 * <h3>方法功能描述:根据主键删除对应的数据</h3> 36 * </p> 37 * @param id 38 * @procedure 执行过程 39 * @see IBaseDao 40 */ 41 //不明确id的类型,就用Serializable 42 void delete(Serializable id); 43 44 /** 45 * 46 * <p> 47 * <h3>方法功能描述:根据数据对象删除数据库中对应的数据</h3> 48 * </p> 49 * @param record 50 * @procedure 执行过程 51 * @see IBaseDao 52 */ 53 void delete(T record); 54 55 /** 56 * 57 * <p> 58 * <h3>方法功能描述:根据指定的对象修改对应的数据</h3> 59 * </p> 60 * @param record 61 * @procedure 执行过程 62 * @see IBaseDao 63 */ 64 void update(T record); 65 66 /** 67 * 68 * <p> 69 * <h3>方法功能描述:根据主键查询对应的数据</h3> 70 * </p> 71 * @param id 72 * @return 返回查找到的数据,如果没有返回null 73 * @procedure 执行过程 74 * @see IBaseDao 75 */ 76 T findById(Serializable id); 77 78 /** 79 * 80 * <p> 81 * <h3>方法功能描述:根据指定的hql语句和参数查询语句</h3> 82 * </p> 83 * @param hql 需要执行的查询的HQL语句 84 * @param params 执行的查询的HQL语句所需的参数,如果没有填写null 85 * @return 返回查询数据的集合,如果出现异常返回null 86 * @procedure 执行过程 87 * @see IBaseDao 88 */ 89 List<T> find(String hql,Map<String, Object> params); 90 91 /** 92 * 93 * <p> 94 * <h3>方法功能描述:根据指定的HQL语句和参数以及分页所需的数据执行查询</h3> 95 * </p> 96 * @param hql 需要执行的查询的HQL语句 97 * @param pageIndex 需要查询的页数 98 * @param pageSize 每页显示的数据条数 99 * @param params 执行的查询的HQL语句所需的参数,如果没有填写null 100 * @return 返回分页查询的结果,是一个Map对象,该对象包含<blockquote> 101 * <b>data</b>:查询结果的数据集合是一个List对象<br> 102 * <b>pageIndex</b>:当前查询的页数<br> 103 * <b>pageSize</b>:每页显示的数据条数<br> 104 * <b>total</b>:数据的总条数<br> 105 * <b>pageTotal</b>:数据的总页数<br> 106 * <b>hasPrev</b>:是否有上一条数据<br> 107 * <b>hasNext</b>:是否有下一条数据<br> 108 * </blockquote> 109 * @procedure 执行过程 110 * @see IBaseDao 111 */ 112 Map<String, Object> find(String hql, int pageIndex, int pageSize, Map<String, Object> params); 113 114 /** 115 * 116 * <p> 117 * <h3>方法功能描述:分页查询数据</h3> 118 * </p> 119 * @param pageIndex 需要查询的页数 120 * @param pageSize 每页显示的数据条数 121 * @return 返回分页查询的结果,是一个Map对象,该对象包含<blockquote> 122 * <b>data</b>:查询结果的数据集合是一个List对象<br> 123 * <b>pageIndex</b>:当前查询的页数<br> 124 * <b>pageSize</b>:每页显示的数据条数<br> 125 * <b>total</b>:数据的总条数<br> 126 * <b>pageTotal</b>:数据的总页数<br> 127 * <b>hasPrev</b>:是否有上一条数据<br> 128 * <b>hasNext</b>:是否有下一条数据<br> 129 * </blockquote> 130 * @procedure 执行过程 131 * @see IBaseDao 132 */ 133 Map<String, Object> find(int pageIndex, int pageSize); 134 135 /** 136 * 137 * <p> 138 * <h3>方法功能描述:根据DetachedCriteria 对象设置的条件查询数据,该功能不具备分页操作</h3> 139 * </p> 140 * @param detachedCriteria 需要设置的对象查询条件 141 * @return 返回查询数据的集合,如果出现异常返回null 142 * @procedure 执行过程 143 * @see IBaseDao 144 */ 145 List<T> find(DetachedCriteria detachedCriteria); 146 147 148 /** 149 * 150 * <p> 151 * <h3>方法功能描述:根据DetachedCriteria 对象设置的条件进行分页查询</h3> 152 * </p> 153 * @param detachedCriteria 需要设置的对象查询条件 154 * @param pageIndex 需要查询的页数 155 * @param pageSize 每页显示的数据条数 156 * @return 返回分页查询的结果,是一个Map对象,该对象包含<blockquote> 157 * <b>data</b>:查询结果的数据集合是一个List对象<br> 158 * <b>pageIndex</b>:当前查询的页数<br> 159 * <b>pageSize</b>:每页显示的数据条数<br> 160 * <b>total</b>:数据的总条数<br> 161 * <b>pageTotal</b>:数据的总页数<br> 162 * <b>hasPrev</b>:是否有上一条数据<br> 163 * <b>hasNext</b>:是否有下一条数据<br> 164 * </blockquote> 165 * @procedure 拼接HQL语句 166 * @see IBaseDao 167 */ 168 Map<String, Object> find(DetachedCriteria detachedCriteria, int pageIndex, int pageSize) 169 170 }
b.IBaseDao接口实现类--BaseDao
1 package com.Elastic.SpringDemo1.ivy.dao; 2 3 import java.io.Serializable; 4 import java.lang.reflect.ParameterizedType; 5 import java.util.HashMap; 6 import java.util.List; 7 import java.util.Map; 8 9 import org.hibernate.Criteria; 10 import org.hibernate.Query; 11 import org.hibernate.Session; 12 import org.hibernate.criterion.DetachedCriteria; 13 import org.hibernate.criterion.Projections; 14 15 import com.Elastic.SpringDemo1.ivy.util.HibernateUtil; 16 //忽略警告 17 @SuppressWarnings({ "rawtypes", "unchecked" }) 18 public class BaseDao<T> implements IBaseDao<T>{ 19 20 private Class entityClass; 21 22 public BaseDao(){ 23 entityClass = this.getEntityClass(); 24 } 25 26 /** 27 * 28 * <p> 29 * <h3>方法功能描述:根据反射得到当前泛型参数(实体类)的数据类型</h3> 30 * </p> 31 * @return 32 * @procedure 执行过程 33 * @see BaseDao 34 */ 35 private Class getEntityClass(){ 36 try { 37 ParameterizedType paramsType = (ParameterizedType)this.getClass().getGenericSuperclass();//只能通过父类得到 38 return (Class)paramsType.getActualTypeArguments()[0]; 39 } catch (Exception e) { 40 e.printStackTrace(); 41 } 42 return null; 43 } 44 45 @Override 46 public Session getSession() { 47 return HibernateUtil.getSession(); 48 } 49 50 private Map<String, Object> createPageData(List<T> data, int pageIndex, int pageSize, int total) { 51 Map<String, Object> map = new HashMap<String, Object>(); 52 53 //获得总页数 54 int pageTotal = (int)Math.ceil((double)total / pageSize); 55 map.put("data", data); 56 map.put("pageIndex", pageIndex); 57 map.put("pageSize", pageSize); 58 map.put("total", total); 59 map.put("pageTotal", pageTotal); 60 61 //boolean,若没赋值,默认true 62 map.put("hasPrev", pageIndex > 1); 63 map.put("hasNext", pageIndex < pageTotal); 64 return map; 65 } 66 67 /* (non-Javadoc) 68 * @see com.Elastic.StrutsDemo2.ivy.dao.IBaseDao#save(java.lang.Object) 69 */ 70 @Override 71 public void save(T record) { 72 this.getSession().save(record); 73 74 } 75 76 /* (non-Javadoc) 77 * @see com.Elastic.StrutsDemo2.ivy.dao.IBaseDao#delete(java.io.Serializable) 78 */ 79 @Override 80 public void delete(Serializable id) { 81 this.getSession().delete(this.findById(id)); 82 83 } 84 85 /* (non-Javadoc) 86 * @see com.Elastic.StrutsDemo2.ivy.dao.IBaseDao#delete(java.lang.Object) 87 */ 88 @Override 89 public void delete(T record) { 90 this.getSession().delete(record); 91 92 } 93 94 /* (non-Javadoc) 95 * @see com.Elastic.StrutsDemo2.ivy.dao.IBaseDao#update(java.lang.Object) 96 */ 97 @Override 98 public void update(T record) { 99 this.getSession().update(record); 100 101 } 102 103 /* (non-Javadoc) 104 * @see com.Elastic.StrutsDemo2.ivy.dao.IBaseDao#findById(java.io.Serializable) 105 */ 106 @Override 107 public T findById(Serializable id) { 108 return (T) this.getSession().get(entityClass, id); 109 } 110 111 /* (non-Javadoc) 112 * @see com.Elastic.StrutsDemo2.ivy.dao.IBaseDao#find(java.lang.String, java.util.Map) 113 */ 114 @Override 115 public List<T> find(String hql, Map<String, Object> params) { 116 Query query = this.getSession().createQuery(hql); 117 query.setProperties(params); 118 return query.list(); 119 } 120 121 /* (non-Javadoc) 122 * @see com.Elastic.StrutsDemo2.ivy.dao.IBaseDao#find(java.lang.String, int, int, java.util.Map) 123 */ 124 @Override 125 public Map<String, Object> find(String hql, int pageIndex, int pageSize, Map<String, Object> params) { 126 String hqlCount; 127 //通过给定的HQL语句查询全部条数 128 int i = hql.indexOf("from"); 129 if (i == 0) { 130 hqlCount = "select count(*) " + hql; 131 } else { 132 hqlCount = "select count(*) " + hql.substring(i); 133 } 134 135 Query query = this.getSession().createQuery(hql); 136 query.setProperties(params); 137 138 //index从0开始 139 query.setFirstResult((pageIndex - 1) * pageSize); 140 query.setMaxResults(pageSize); 141 142 int total = Integer.parseInt(this.getSession().createQuery(hqlCount).uniqueResult().toString()); 143 return this.createPageData(query.list(), pageIndex, pageSize, total); 144 } 145 146 /* (non-Javadoc) 147 * @see com.Elastic.StrutsDemo2.ivy.dao.IBaseDao#find(int, int) 148 */ 149 @Override 150 public Map<String, Object> find(int pageIndex, int pageSize) { 151 Criteria criteria = this.getSession().createCriteria(entityClass); 152 153 //查询总数 154 criteria.setProjection(Projections.rowCount()); 155 int total = Integer.parseInt(criteria.uniqueResult().toString()); 156 criteria.setProjection(null); 157 158 criteria.setFirstResult((pageIndex - 1) * pageSize); 159 criteria.setMaxResults(pageSize); 160 return this.createPageData(criteria.list(), pageIndex, pageSize, total); 161 } 162 163 /* (non-Javadoc) 164 * @see com.Elastic.StrutsDemo2.ivy.dao.IBaseDao#find(org.hibernate.criterion.DetachedCriteria) 165 */ 166 public List<T> find(DetachedCriteria detachedCriteria) { 167 return detachedCriteria.getExecutableCriteria(getSession()).list(); 168 } 169 170 /* (non-Javadoc) 171 * @see com.Elastic.StrutsDemo2.ivy.dao.IBaseDao#find(org.hibernate.criterion.DetachedCriteria, int, int) 172 */ 173 @Override 174 public Map<String, Object> find(DetachedCriteria detachedCriteria, int pageIndex, int pageSize) { 175 //查询总数 176 int total = Integer.parseInt(detachedCriteria.getExecutableCriteria(getSession()) 177 .setProjection(Projections.rowCount()) 178 .uniqueResult().toString()); 179 180 //分页查询 181 Criteria criteria = detachedCriteria.getExecutableCriteria(getSession()); 182 criteria.setFirstResult((pageIndex - 1) * pageSize); 183 criteria.setMaxResults(pageSize); 184 return this.createPageData(criteria.list(), pageIndex, pageSize, total); 185 } 186 }
c.具体业务UserDao接口
1 package com.Elastic.SpringDemo1.ivy.dao; 2 3 import java.io.Serializable; 4 5 import com.Elastic.SpringDemo1.ivy.entity.User; 6 public interface UserDao extends IBaseDao<User>{ 7 }
5.dao.impl包
a.UserDaoImpl
1 package com.Elastic.SpringDemo1.ivy.dao.impl; 2 3 import java.io.Serializable; 4 import java.util.List; 5 import java.util.Map; 6 7 import org.hibernate.Session; 8 import org.hibernate.criterion.DetachedCriteria; 9 10 import com.Elastic.SpringDemo1.ivy.dao.BaseDao; 11 import com.Elastic.SpringDemo1.ivy.dao.UserDao; 12 import com.Elastic.SpringDemo1.ivy.entity.User; 13 14 public class UserDaoImpl extends BaseDao<User> implements UserDao { 15 16 @Override 17 public User findById(Serializable id) { 18 if ("admin".equals(id.toString().trim())) { 19 User user = new User(); 20 user.setLoginName("admin"); 21 user.setLoginPass("123456"); 22 return user; 23 } 24 return null; 25 } 26 }
a2.list -- UserDaoImpl
1 package com.Elastic.SpringDemo1.ivy.dao.impl; 2 3 import java.io.Serializable; 4 import java.util.List; 5 import java.util.Map; 6 7 import org.hibernate.Session; 8 import org.hibernate.criterion.DetachedCriteria; 9 10 import com.Elastic.SpringDemo1.ivy.dao.BaseDao; 11 import com.Elastic.SpringDemo1.ivy.dao.UserDao; 12 import com.Elastic.SpringDemo1.ivy.entity.User; 13 14 public class UserDaoImpl extends BaseDao<User> implements UserDao { 15 private List<User> list; 16 17 18 public List<User> getList() { 19 return list; 20 } 21 22 public void setList(List<User> list) { 23 this.list = list; 24 } 25 26 @Override 27 public User findById(Serializable id) { 28 for (User user : list) { 29 if (user.getLoginName().trim().equals(id.toString().trim())) { 30 return user; 31 } 32 } 33 return null; 34 } 35 }
6.service包
a.UserService接口
1 package com.Elastic.SpringDemo1.ivy.service; 2 3 import com.Elastic.SpringDemo1.ivy.entity.User; 4 5 public interface UserService { 6 User login(String name,String pass); 7 }
7.service.impl包
a.带参构造方法 --UserServiceImpl
1 package com.Elastic.SpringDemo1.ivy.service.impl; 2 3 import com.Elastic.SpringDemo1.ivy.dao.UserDao; 4 import com.Elastic.SpringDemo1.ivy.entity.User; 5 import com.Elastic.SpringDemo1.ivy.service.UserService; 6 7 public class UserServiceImpl implements UserService { 8 private UserDao userDao; 9 10 public UserDao getUserDao() { 11 return userDao; 12 } 13 14 public void setUserDao(UserDao userDao) { 15 this.userDao = userDao; 16 } 17 18 public UserServiceImpl(UserDao userDao) { 19 this.userDao = userDao; 20 } 21 22 @Override 23 public User login(String name, String pass) { 24 User user = userDao.findById(name); 25 /*if ("admin".equals(name.trim()) && "123456".equals(pass.trim())) { 26 User user = new User(); 27 user.setLoginName("admin"); 28 user.setLoginPass("123456");; 29 return user; 30 }*/ 31 if (null != user && pass.equals(user.getLoginPass())) { 32 return user; 33 } 34 return null; 35 } 36 }
a2.无参构造方法 --UserServiceImpl
1 package com.Elastic.SpringDemo1.ivy.service.impl; 2 3 import com.Elastic.SpringDemo1.ivy.dao.UserDao; 4 import com.Elastic.SpringDemo1.ivy.entity.User; 5 import com.Elastic.SpringDemo1.ivy.service.UserService; 6 7 public class UserServiceImpl implements UserService { 8 private UserDao userDao; 9 10 public UserDao getUserDao() { 11 return userDao; 12 } 13 14 public void setUserDao(UserDao userDao) { 15 this.userDao = userDao; 16 } 17 18 @Override 19 public User login(String name, String pass) { 20 User user = userDao.findById(name); 21 if (null != user && pass.equals(user.getLoginPass())) { 22 return user; 23 } 24 return null; 25 } 26 }
b.UserDaoImplT
1 package com.Elastic.SpringDemo1.ivy.dao.impl; 2 3 import com.Elastic.SpringDemo1.ivy.dao.BaseDao; 4 import com.Elastic.SpringDemo1.ivy.dao.UserDao; 5 import com.Elastic.SpringDemo1.ivy.entity.User; 6 7 public class UserDaoImplT extends BaseDao<User> implements UserDao { 8 9 }
8.Spring配置文件
a.带参构造方法 -- userContext.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans.xsd"> 6 7 8 <!-- 由Spring的IoC容器创建对象 --> 9 <!-- 方法1 --> 10 <bean id="userService" class="com.Elastic.SpringDemo1.ivy.service.impl.UserServiceImpl"> 11 <constructor-arg> 12 <bean class="com.Elastic.SpringDemo1.ivy.dao.impl.UserDaoImpl"></bean> 13 </constructor-arg> 14 </bean> 15 16 <!-- 方法2 --> 17 <bean id="userDao" class="com.Elastic.SpringDemo1.ivy.dao.impl.UserDaoImpl"></bean> 18 19 <bean id="userService" class="com.Elastic.SpringDemo1.ivy.service.impl.UserServiceImpl" p:userDao-ref="userDao"> 20 <constructor-arg> 21 <ref bean="userDao"></ref> 22 </constructor-arg> 23 </bean> 24 </beans>
a2.带参构造方法 + list --userContext.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:p="http://www.springframework.org/schema/p" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd"> 7 8 <bean id="userDao" class="com.Elastic.SpringDemo1.ivy.dao.impl.UserDaoImpl"> 9 <!-- 设置一个测试数据 --> 10 <property name="list"> 11 <list> 12 <bean class="com.Elastic.SpringDemo1.ivy.entity.User"> 13 <property name="loginName" value="admin"></property> 14 <property name="loginPass" value="123456"></property> 15 </bean> 16 <bean class="com.Elastic.SpringDemo1.ivy.entity.User"> 17 <property name="loginName" value="test"></property> 18 <property name="loginPass" value="123456"></property> 19 </bean> 20 <bean class="com.Elastic.SpringDemo1.ivy.entity.User"> 21 <property name="loginName" value="admin"></property> 22 <property name="loginPass" value="123456"></property> 23 </bean> 24 <bean class="com.Elastic.SpringDemo1.ivy.entity.User"> 25 <property name="loginName" value="admintest"></property> 26 <property name="loginPass" value="123456"></property> 27 </bean> 28 29 <!-- 使用P命名空间完成复制 --> 30 <bean class="com.Elastic.SpringDemo1.ivy.entity.User" p:loginName="admin123" p:loginPass="abcd123" > 31 </bean> 32 33 </list> 34 </property> 35 </bean> 36 37 <!-- 由Spring的IoC容器创建对象 --> 38 <bean id="userService" class="com.Elastic.SpringDemo1.ivy.service.impl.UserServiceImpl" p:userDao-ref="userDao"> 39 <constructor-arg> 40 <ref bean="userDao"></ref> 41 </constructor-arg> 42 </bean> 43 </beans>
a3.带参构造 + 连接数据库 -- userContext.xml
1 a4.P命名空间(对象) + 无参构造方法 -- userContext.xml 2 <?xml version="1.0" encoding="UTF-8"?> 3 <beans xmlns="http://www.springframework.org/schema/beans" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xmlns:p="http://www.springframework.org/schema/p" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans.xsd"> 8 9 <!-- 外部bean,都可引用 --> 10 <bean id="userDao" class="com.Elastic.SpringDemo1.ivy.dao.impl.UserDaoImpl"> 11 <!-- 设置一个测试数据 --> 12 <property name="list"> 13 <list> 14 <!-- 内部bean,不能引用 --> 15 <bean class="com.Elastic.SpringDemo1.ivy.entity.User"> 16 <property name="loginName" value="admin"></property> 17 <property name="loginPass" value="123456"></property> 18 </bean> 19 <bean class="com.Elastic.SpringDemo1.ivy.entity.User"> 20 <property name="loginName" value="test"></property> 21 <property name="loginPass" value="123456"></property> 22 </bean> 23 <bean class="com.Elastic.SpringDemo1.ivy.entity.User"> 24 <property name="loginName" value="admin"></property> 25 <property name="loginPass" value="123456"></property> 26 </bean> 27 <bean class="com.Elastic.SpringDemo1.ivy.entity.User"> 28 <property name="loginName" value="admintest"></property> 29 <property name="loginPass" value="123456"></property> 30 </bean> 31 32 <!-- 使用P命名空间完成复制 --> 33 <bean class="com.Elastic.SpringDemo1.ivy.entity.User" > 34 <property name="loginPass"> 35 <null></null> 36 </property> 37 </bean> 38 39 </list> 40 </property> 41 </bean> 42 43 <!-- 连接数据库测试 --> 44 <bean id="userDaoImpl" class="com.Elastic.SpringDemo1.ivy.dao.impl.UserDaoImplT"></bean> 45 46 <!-- 由Spring的IoC容器创建对象 --> 47 <bean id="userService" class="com.Elastic.SpringDemo1.ivy.service.impl.UserServiceImpl" p:userDao-ref="userDao"> 48 </bean> 49 </beans>
9.test包
1 package com.Elastic.SpringDemo1.ivy.test; 2 3 import java.util.Scanner; 4 5 import org.springframework.context.ApplicationContext; 6 import org.springframework.context.support.ClassPathXmlApplicationContext; 7 8 import com.Elastic.SpringDemo1.ivy.entity.User; 9 import com.Elastic.SpringDemo1.ivy.service.UserService; 10 11 public class TestUser { 12 13 public static void main(String[] args) { 14 ApplicationContext context = new ClassPathXmlApplicationContext("userContext.xml"); 15 UserService userService = (UserService)context.getBean("userService"); 16 Scanner input = new Scanner(System.in); 17 String name = input.next(); 18 String pass = input.next(); 19 User user = userService.login(name, pass); 20 if (null == user) { 21 System.out.println("登录失败"); 22 } else { 23 System.out.println("登录成功"); 24 } 25 } 26 27 }