程序的耦合
耦合:程序间的依赖关系
包括:
类之间的依赖
方法间的依赖
解耦:
降低程序间的依赖关系
实际开发中:
应该做到:编译期不依赖,运行时才依赖。
解耦的思路:
第一步:使用反射来创建对象,而避免使用new关键字。
第二步:通过读取配置文件来获取要创建的对象全限定类名
* 示例:
public static void main(String[] args) throws Exception{
// 1.注册驱动
// 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();
}
/**
* 一个创建Bean对象的工厂
*
* Bean:在计算机英语中,有可重用组件的含义。
* JavaBean:用java语言编写的可重用组件。
* javabean > 实体类
*
* 它就是创建我们的service和dao对象的。
*
* 第一个:需要一个配置文件来配置我们的service和dao
* 配置的内容:唯一标识=全限定类名(key=value)
* 第二个:通过读取配置文件中配置的内容,反射创建对象
*
* 我的配置文件可以是xml也可以是properties
*/
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;
}*/
}
IOC
spring基于 XML 的配置
* bean 标签:用于配置让 spring 创建对象,并且存入 ioc 容器之中
* id 属性:对象的唯一标识。
* class 属性:指定要创建对象的全限定类名
1.在类的根路径下创建一个任意名称的 xml 文件(不能是中文)bean.xml:
<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.xsd">
<!-- 配置 service -->
<bean id="accountService" class="com.demo.service.impl.AccountServiceImpl">
</bean>
<!-- 配置 dao -->
<bean id="accountDao" class="com.demo.dao.impl.AccountDaoImpl"></bean>
</beans>
2.使用:
public static void main(String[] args) {
//1.使用 ApplicationContext 接口,就是在获取 spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 bean 的 id 获取对象
IAccountService aService = (IAccountService) ac.getBean("accountService");
System.out.println(aService);
IAccountDao aDao = (IAccountDao) ac.getBean("accountDao");
System.out.println(aDao);
}
细节
ApplicationContext 接口的实现类
* ClassPathXmlApplicationContext:
它是从类的根路径下加载配置文件,推荐使用这种
* FileSystemXmlApplicationContext:(不常用)
它是从磁盘路径上加载配置文件,配置文件可以在磁盘的任意位置。
* AnnotationConfigApplicationContext:
当我们使用注解配置容器对象时,需要使用此类来创建 spring 容器。它用来读取注解。
BeanFactory 和 ApplicationContext 的区别
* BeanFactory 才是 Spring 容器中的顶层接口。
* ApplicationContext 是它的子接口。
* BeanFactory 和 ApplicationContext 的区别:
* 创建对象的时间点不一样。
1.ApplicationContext:只要一读取配置文件,默认情况下就会创建对象。单例对象适用。更多采用此接口
2.BeanFactory:什么使用什么时候创建对象。多例对象适用。
实例化 Bean 的三种方式
1.使用默认无参构造函数
在默认情况下:它会根据默认无参构造函数来创建类对象。如果 bean 中没有默认无参构造函数,将会创建失败。
<bean id="accountService" class="com.demo.service.impl.AccountServiceImpl"/>
2.spring 管理静态工厂-使用静态工厂的方法创建对象
/**
* 模拟一个静态工厂,创建业务层实现类
*/
public class StaticFactory {
public static IAccountService createAccountService(){
return new AccountServiceImpl();
}
}
<bean id="accountService"
class="com.demo.factory.StaticFactory"
factory-method="createAccountService"></bean>
此种方式是:
* 使用 StaticFactory 类中的静态方法 createAccountService 创建对象,并存入 spring 容器
* id 属性:指定 bean 的 id,用于从容器中获取
* class 属性:指定静态工厂的全限定类名
* factory-method 属性:指定生产对象的静态方法
3.spring 管理实例工厂-使用实例工厂的方法创建对象
/**
* 模拟一个实例工厂,创建业务层实现类
* 此工厂创建对象,必须现有工厂实例对象,再调用方法
*/
public class InstanceFactory {
public IAccountService createAccountService(){
return new AccountServiceImpl();
}
}
<bean id="instancFactory" class="com.demo.factory.InstanceFactory"></bean>
<bean id="accountService"
factory-bean="instancFactory"
factory-method="createAccountService"></bean>
此种方式是:
* 先把工厂的创建交给 spring 来管理。
* 然后在使用工厂的 bean 来调用里面的方法
* factory-bean 属性:用于指定实例工厂 bean 的 id。
* factory-method 属性:用于指定实例工厂中创建对象的方法。
bean的作用范围
- scope:指定对象的作用范围
* singleton :默认值,单例的
* prototype :多例的
* request :作用于web应用的请求范围
* session :作用于web应用的会话范围
* global-session:作用于集群环境的会话范围(全局会话范围),当不是集群环境时,它就是session。(负载均衡调度集群服务器)
bean的生命周期
单例对象:scope="singleton"
一个应用只有一个对象的实例。它的作用范围就是整个引用。
生命周期:
出生:当应用加载,创建容器时,对象就被创建了。
活着:只要容器在,对象一直活着。
死亡:当应用卸载,销毁容器时,对象就被销毁了。
配置:init-method="" destroy-method=""
* 注意:必须调用spring容器的close方法才有效
多例对象:scope="prototype"
每次访问对象时,都会重新创建对象实例。
生命周期:
出生:当使用对象时,创建新的对象实例。
活着:只要对象在使用中,就一直活着。
死亡:当对象长时间不用时,被 java 的垃圾回收器回收了。
spring的依赖注入:Dependency Injection
1.IOC的作用:降低程序间的耦合(依赖关系)
2.依赖关系的管理:以后都交给spring来维护
3.在当前类需要用到其他类的对象,由spring为我们提供,我们只需要在配置文件中说明
4:依赖关系的维护:就称之为依赖注入
5:依赖注入能注入的数据类型:
* 基本类型和String
* 其他bean类型(在配置文件中或者注解配置过的bean)
* 复杂类型/集合类型
6:注入的方式:
* 使用构造函数提供
* 使用set方法提供
* 使用注解提供(在spring基于注解配置时使用)
构造函数注入:
使用的标签:constructor-arg
标签出现的位置:bean标签的内部
标签中的属性
type:用于指定要注入的数据的数据类型,该数据类型也是构造函数中某个或某些参数的类型
index:用于指定要注入的数据给构造函数中指定索引位置的参数赋值。索引的位置是从0开始
name:用于指定给构造函数中指定名称的参数赋值(常用的)
====================以上三个用于指定给构造函数中哪个参数赋值============================
value:用于提供基本类型和String类型的数据
ref:用于指定其他的bean类型数据。它指的就是在spring的Ioc核心容器中出现过的bean对象
优势:
在获取bean对象时,注入数据是必须的操作,否则对象无法创建成功。
弊端:
改变了bean对象的实例化方式,使我们在创建对象时,如果用不到这些数据,也必须提供。
<bean id="accountService" class="com.demo.service.impl.AccountServiceImpl">
<constructor-arg name="name" value="泰斯特"></constructor-arg>
<constructor-arg name="age" value="18"></constructor-arg>
<constructor-arg name="birthday" ref="now"></constructor-arg>
</bean>
<!-- 配置一个日期对象 -->
<bean id="now" class="java.util.Date"></bean>
set方法注入(更常用的方式)
涉及的标签:property
出现的位置:bean标签的内部
标签的属性
name:用于指定注入时所调用的set方法名称
value:用于提供基本类型和String类型的数据
ref:用于指定其他的bean类型数据。它指的就是在spring的Ioc核心容器中出现过的bean对象
优势:
创建对象时没有明确的限制,可以直接使用默认构造函数
弊端:
如果有某个成员必须有值,则获取对象时有可能set方法没有执行。
<bean id="accountService2" class="com.demo.service.impl.AccountServiceImpl2">
<property name="name" value="TEST" ></property>
<property name="age" value="21"></property>
<property name="birthday" ref="now"></property>
</bean>
<!-- 复杂类型的注入/集合类型的注入
用于给List结构集合注入的标签:
list array set
用于个Map结构集合注入的标签:
map props
结构相同,标签可以互换
-->
<bean id="accountService3" class="com.demo.service.impl.AccountServiceImpl3">
<property name="myStrs">
<set>
<value>AAA</value>
<value>BBB</value>
<value>CCC</value>
</set>
</property>
<property name="myList">
<array>
<value>AAA</value>
<value>BBB</value>
<value>CCC</value>
</array>
</property>
<property name="mySet">
<list>
<value>AAA</value>
<value>BBB</value>
<value>CCC</value>
</list>
</property>
<property name="myMap">
<props>
<prop key="testC">ccc</prop>
<prop key="testD">ddd</prop>
</props>
</property>
<property name="myProps">
<map>
<entry key="testA" value="aaa"></entry>
<entry key="testB">
<value>BBB</value>
</entry>
</map>
</property>
</bean>
spring基于注解的配置
账户的业务层实现类
曾经XML的配置:
<bean id="accountService" class="com.demo.service.impl.AccountServiceImpl"
scope="" init-method="" destroy-method="">
<property name="" value="" | ref=""></property>
</bean>
现在XML的配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,而是一个名称为
context名称空间和约束中-->
<context:component-scan base-package="com.demo"></context:component-scan>
用于创建对象的
他们的作用就和在XML配置文件中编写一个<bean>标签实现的功能是一样的
- Component:
1. 作用:用于把当前类对象存入spring容器中
2. 属性:- value:用于指定bean的id。当我们不写时,它的默认值是当前类名,且首字母改小写。
- Controller:一般用在表现层
- Service:一般用在业务层
- Repository:一般用在持久层
以上三个注解他们的作用和属性与Component是一模一样。
他们三个是spring框架为我们提供明确的三层使用的注解,使我们的三层对象更加清晰
用于注入数据的
他们的作用就和在xml配置文件中的bean标签中写一个<property>标签的作用是一样的
- Autowired:
1. 作用:自动按照类型注入。只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功
2. 如果ioc容器中没有任何bean的类型和要注入的变量类型匹配,则报错。
3. 如果Ioc容器中有多个类型匹配时,会根据变量名称匹配,如果没有任何可以匹配的,则报错。
4. 注意:- 出现位置:
可以是变量上,也可以是方法上 - 细节:
在使用注解注入时,set方法就不是必须的了。
- 出现位置:
- Qualifier:必须搭配Autowired一起使用
1. 作用:在按照类型注入的基础之上再按照名称注入。它在给类成员注入时不能单独使用。但是在给方法参数注入时可以
2. 属性:- value:用于指定注入bean的id。
- Resource:解决了Qualifier的弊端
1. 作用:直接按照bean的id注入。它可以独立使用
2. 属性:- name:用于指定bean的id。
以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现。
另外,集合类型的注入只能通过XML来实现。
- Value
1. 作用:用于注入基本类型和String类型的数据
2. 属性:- value:用于指定数据的值。它可以使用spring中SpEL(也就是spring的el表达式)
- SpEL的写法:${表达式}
用于改变作用范围的
他们的作用就和在bean标签中使用scope属性实现的功能是一样的
- Scope
1. 作用:用于指定bean的作用范围
2. 属性:- value:指定范围的取值。常用取值:singleton prototype
和生命周期相关
他们的作用就和在bean标签中使用init-method和destroy-methode的作用是一样的
- PreDestroy
1. 作用:用于指定销毁方法 - PostConstruct
1. 作用:用于指定初始化方法