SpringSpring的定义Spring特点Spring的体系结构结合JDBC分析程序中出现的问题编写工厂类和配置文件完成解耦 Spring特点 Spring的体系结构 结合JDBC分析程序中出现的问题 编写工厂类和配置文件完成解耦

一站式Java框架 核心 IoC(控制反转), AOP(面向切面编程) , 便于整合第三方框架

Spring特点

  • 非侵入式
  • 方便集成
  • 方便解耦

Spring的体系结构

Spring体系结构

Core Contraniner : IoC

IoC 基础上提供了AOP

Spring 是容器, 底层是工厂 我们通过Spring来创建对象

结合JDBC分析程序中出现的问题

  1. 新建一手Maven项目
  2. pom.xml 引入坐标
  3. 补全目录 java, resources
  4. 写jdbc的Demo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    public static void (String[] args) throws  Exception{

// DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName("com.mysql.jdbc.Driver");

//2.获取连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/eesy","root","1234");
//3.获取操作数据库的预处理对象
PreparedStatement pstm = conn.prepareStatement("select * from account");
//4.执行SQL,得到结果集
ResultSet rs = pstm.executeQuery();
//5.遍历结果集
while(rs.next()){
System.out.println(rs.getString("name"));
}
//6.释放资源
rs.close();
pstm.close();
conn.close();
}
  1. 发现一个问题 如果没有mysql的驱动 该程序就不能运行 这里就是 程序间的耦合

现在 解决类之间的依赖关系 , 降低类之间的依赖关系, 也就是 解耦

实际开发中做到 编译期不依赖, 运行时才依赖.

解耦的思路 :

  1. 使用反射来创建对象, 避免使用new
  2. 通过读取配置文件来获取创建对象的全限定类名

编写工厂类和配置文件完成解耦

Bean: 可重用组件 创建service和dao对象

JavaBean: Java编写的可重用组件

实体类: 通常与数据库有直接联系

  1. 搭建Java项目 标准三层架构
  2. bean.properties 将 dao , service 以 key = value 形式 编写
  3. 编写 BeanFactory 读取 bean.properties
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

public class BeanFactory {
//定义一个Properties对象
private static Properties props;

//定义一个Map,用于存放我们要创建的对象。我们把它称之为容器
private static Map<String,Object> beans;

//使用静态代码块为Properties对象赋值
static {
try {
//实例化对象
props = new Properties();
// 不要使用 相对路径和磁盘绝对路径 使用当前类的类加载器获取配置文件
//获取properties文件的流对象
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
props.load(in);
//实例化容器
beans = new HashMap<String,Object>();
//取出配置文件中所有的Key
Enumeration keys = props.keys();
//遍历枚举
while (keys.hasMoreElements()){
//取出每个Key
String key = keys.nextElement().toString();
//根据key获取value
String beanPath = props.getProperty(key);
//反射创建对象
Object value = Class.forName(beanPath).newInstance();
//把key和value存入容器中
beans.put(key,value);
}
}catch(Exception e){
throw new ExceptionInInitializerError("初始化properties失败!");
}
}

/**
* 根据bean的名称获取对象
* @param beanName
* @return
*/
public static Object getBean(String beanName){
return beans.get(beanName);
}

/**
* 根据Bean的名称获取bean对象
* @param beanName
* @return

public static Object getBean(String beanName){
Object bean = null;
try {
String beanPath = props.getProperty(beanName);
// System.out.println(beanPath);
bean = Class.forName(beanPath).newInstance();//每次都会调用默认构造函数创建对象 所以多例对象 怎么能保证对象的唯一性? 对象创建完毕 马上存起来
}catch (Exception e){
e.printStackTrace();
}
return bean;
}*/
}