Spring-IOC
IOC(Inversion of Control)意为控制反转,把创建对象的权利交给框架,是框架的重要特征,IOC 的作用是消减程序的耦合,解除我们代码中的依赖关系
下面我们主要说明基于XML 文件来使用 IOC 的过程,以及使用 XML 文件创建 bean 的三种方式
通过配置 XML 文件实现 IOC
首先我这里是使用 Maven 工程创建的 Spring java 工程,而不是 java web 工程,首先我们已经配置了 Spring 的开发环境,pom.xml文件、IAccountService、IAccountDao、AccountServiceImpl、AccountDaoImpl以及测试类Client等,代码如下(此处可以跳过)
pom.xml:
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
</dependencies>
IAccountService:
package com.lmh.service;
/**
* 账户业务层的接口
*/
public interface IAccountService {
/**
* 模拟保存账户
*/
void saveAccount();
}
IAccountDao:
package com.lmh.dao;
/**
* 账户的持久层接口
*/
public interface IAccountDao {
void saveAccount();
}
AccountServiceImpl:
package com.lmh.service.impl;
import com.lmh.dao.IAccountDao;
import com.lmh.dao.impl.AccountDaoImpl;
import com.lmh.service.IAccountService;
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl implements IAccountService {
public AccountServiceImpl() {
}
@Override
public void saveAccount() {
System.out.println("save service");
}
}
AccountDaoImpl:
package com.lmh.dao.impl;
import com.lmh.dao.IAccountDao;
public class AccountDaoImpl implements IAccountDao {
/**
* 账户的持久层实现类
*/
@Override
public void saveAccount() {
System.out.println("dao save");
}
}
配置 XML 文件
首先我们将 Spring 官方文档中的配置文件规范复制下来,粘贴到resource文件夹下的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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
接下来我们要在<beans>标签中创建<bean>子标签,在 Spring 中,每个 bean 都是一个对象,Spring 通过这种方式,解除程序中使用new创建对象的高耦合,也就是说,创建对象的过程,Spring 框架都为我们做了
XML 中三种配置 bean 的方法
使用默认构造函数创建
在<beans>标签中添加如下<bean>标签
<bean id="accountService" class="com.lmh.service.impl.AccountServiceImpl"></bean>
在 Spring 的配置文件中使用<bean>标签,配以id和class属性之后,且没有其他属性和标签时采用的是默认构造函数创建 bean 对象,此时如果类中没有默认构造函数,则对象无法创建
使用普通工厂方法
这种方法是在需要创建的对象是在另一个不能修改的(jar包中)类中的方法创建的对象时,我们需要通过创建一个工厂的<bean>和所需对象的<bean>两组标签来实现
<bean id="instanceFactory" class="com.lmh.factory.InstanceFactory"></bean>
<bean id="accountDao" factory-bean="instanceFactory" factory-method="getAccountDao"></bean>
被创建的类需要指明 factory 的<bean>标签中的factory-bean属性以确定调用哪个 factory,并通过factory-method属性来指定 factory 的方法名从而调用方法创建对象
使用工厂中的静态方法创建对象
当所需对象是被其他类中的静态方法创建时,我们可以不去创建 factory 对象而直接调用静态方法创建 bean
<bean id="accountService" class="com.lmh.factory.StaticFactory" factory-method="getAccountService"></bean>
来源:CSDN
作者:scfor333
链接:https://blog.csdn.net/scfor333/article/details/104627957