IOC
概念
通常情况下,应用直接跟资源联系,这样两者就产生了必要的联系,这样应用和资源的耦合度就变得很高了,而spring中的ioc则是断开了应用和资源的联系,而是通过一个工厂向应用提供资源,与资源取得联系,将应用所需要的资源通过工厂转发,从而解除了资源和应用之间的必然关系。
控制反转(IOC)
把创建对象的权力交给框架,也可以说将自身控制资源的权力交给spring工厂来控制,从而降低程序间的依赖关系。包括:依赖注入和依赖查找。
作用
降低程序之间的耦合
Spring中IOC的使用
Spring基于xml的IOC开发环境和入门
- 导入spring依赖
<!--sprig依赖包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
- 创建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">
<!--把对象的创建交给spring来管理-->
<!--bean标签中 id为获取对象时的唯一标识 class为反射需要创建的全限定类名-->
<bean id="accountService" class="com.itheima.spring.service.impl.AccountServiceImpl"></bean>
<bean id="accountDao" class="com.itheima.spring.dao.impl.AccountDaoImpl"></bean>
</beans>
- Controller层进行测试
/**
* 模拟一个表现层,用于调用业务层
*/
public class ControllerTest {
/**
* 获取sprig ioc容器,并根据id获取对象
* @param args
*/
public static void main(String[] args) {
//1.获取核心容器
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
//2.根据id获取Bean对象 两种方式
AccountService accountService = (AccountService) context.getBean("accountService");//直接获取在进行强转
AccountDao accountDao = context.getBean("accountDao", AccountDao.class);//根据字节码进行强转
System.out.println(accountService);//com.itheima.spring.service.impl.AccountServiceImpl@46d56d67
System.out.println(accountDao);//com.itheima.spring.dao.impl.AccountDaoImpl@d8355a8
//AccountService accountService = new AccountServiceImpl();
//accountService.saveAccount();
}
}
ApplicationContext接口的三个常用实现类
//可以加载类路径下的配置文件,要求配置文件必须在类路径下,不在的话,加载不了
ApplicationContext context1 = new ClassPathXmlApplicationContext("bean.xml");
//可以加载磁盘任意路径下的配置文件(必须有访问权限)bean.xml的全路径名
ApplicationContext context2 = new FileSystemXmlApplicationContext("D:\\gyf\\my_spring\\spring_ioc_xml\\src\\main\\resources\\bean.xml");
//可以读取注解创建的容器
ApplicationContext context2 = new AnnotationConfigApplicationContext();
ApplicationContext和BeanFactory的区别
-
ApplicationContext:(单例对象适用)一般使用ApplicationContext
它在构建核心容器时,创建对象采取的策略是立即加载的方式,也就是说,只要一读取完配置文件马上就创建配置文件中配置的对象。
-
BeanFactory:(多例对象适用)
它在构建核心容器时,创建对象采取的策略是采用延迟加载的方式,也就是说,什么时候根据id获取对象,什么时候才真正创造对象。
Spring创建Bean的三种方式
- 第一种:使用默认构造函数创建,在配置文件中使用bean标签配以id和class属性之后,没有其他属性和标签时。如果类中没有构造函数,则对象无法创建。
<!--bean标签中 id为获取对象时的唯一标识 class为反射需要创建的全限定类名-->
<bean id="accountService" class="com.itheima.spring.service.impl.AccountServiceImpl"></bean>
- 第二种:使用普通工厂中的方法创建对象(使用某个类中的方法创建对象,并存入spring容器)
/**
* 模拟一个工厂类,该类可能存在于jar包中,我们无法通过修改源码的方式来提供默认构造方法
*/
public class InstanceFactory {
public AccountService getAccountService(){
return new AccountServiceImpl();
}
}
~~~xml
<!--factory-bean指定创建这个类的对象的工厂 factory-method指定哪个方法获取这个对象-->
<bean id="instanceFactory" class="com.itheima.spring.factory.InstanceFactory"></bean>
<bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"></bean>
- 第三种:使用工厂中的静态方法创建对象(使用某个类中的静态方法创建对象,并存入spring容器)
/**
* 模拟工厂类里面是一个静态方法
*/
public class StaticFactory {
public static AccountService getAccountService(){
return new AccountServiceImpl();
}
}
<bean id="accountService" class="com.itheima.spring.factory.StaticFactory" factory-method="getAccountService"></bean>
Bean的作用范围
Bean标签的scope属性
作用:用于指定Bean的作用范围
-
取值:一般使用单例和多例
- singleton:单例的(默认)
<bean id="accountService" class="com.itheima.spring.factory.StaticFactory" factory-method="getAccountService" scope="singleton"></bean>- prototype:多例
<bean id="accountService" class="com.itheima.spring.factory.StaticFactory" factory-method="getAccountService" scope="prototype"></bean>- request:作用于web应用的请求范围
- session:作用于web应用的会话范围
- global-session:作用于集群环境的会话范围(全局会话范围)
Bean对象的生命周期
单例对象
- 出生:当容器创建时对象出生
- 活着:只要容器还在,对象一直活着
- 死亡:容器销毁,对象销毁
总结:单例对象的生命周期和容器相同
多例对象
- 出生:当使用对象时spring为我们创建
- 活着:对象只要在使用时就一直活着
- 死亡:当对象长时间不用且没有别的对象引用时由java的垃圾回收机制回收
spring中的依赖注入
依赖注入:Dependency Injection
IOC的作用:
降低程序间的耦合(依赖关系)-
概念:
依赖关系的管理,都交给spring来维护,在当前类需要用到其他类的对象,由spring为我们提供,我们只需要在配置文件中说明。 -
能注入的三种方式:
- 基本数据类型和String
- 其他bean类型(在配置文件中或者注解配置过的bean)
- 复杂类型/集合类型
-
注入的三种方式:
- 使用构造函数提供
- 使用的标签:constructor-arg
- 标签出现的位置:bean标签的内部
- 标签属性:
- type:用于指定要注入的数据的数据类型,该数据类型也是构造函数中某个或某些参数的类型。
- index:用于指定要注入的数据给构造函数中指定索引位置的参数赋值,索引的位置是从0开始。
- (主要使用)name:用于指定给构造函数中指定名称的参数赋值
- value:用于提供基本数据类型和String类型的数据
- ref:用于指定其他bean类型,指的就是在springIOC核心容器中出现的bean对象
<!--spring的依赖注入--> <bean id="accountService" class="com.itheima.spring.service.impl.AccountServiceImpl"> <!--标签constructor-arg:根据构造函数注入;name标签:用于构造函数中指定的参数赋值;value:用于提供基本数据类型和String类型的数据;ref:用于指定其他bean类型--> <constructor-arg name="name" value="zhangsan" ></constructor-arg> <constructor-arg name="age" value="18" ></constructor-arg> <constructor-arg name="birthday" ref="new" ></constructor-arg> </bean> <!--配置一个日期类--> <bean id="new" class="java.util.Date"></bean>public class AccountServiceImpl implements AccountService { //如果经常发生变化的数据,并不适合注入的方式 private String name; private Integer age; private Date birthday; public AccountServiceImpl(String name, Integer age, Date birthday) { this.name = name; this.age = age; this.birthday = birthday; } public void saveAccount() { System.out.println("service中的saveAccount方法执行了。。。"+name+","+age+","+birthday); //service中的saveAccount方法执行了。。。zhangsan,18,Wed Nov 04 03:59:44 CST 2020 } }优势:在获取bean对象时,注入数据是必须操作,否则对象无法创建成功 弊端:改变了bean对象的实例化方式,使我们在创建对象时,如果用不到这些数据,也必须提供。- 使用set方法提供(更常用)
- 使用的标签:property
- 标签出现的位置:bean标签的内部
- 标签属性:
- name:用于指定注入时所调用的set方法名称
- value:用于提供基本数据类型和String类型的数据
- ref:用于指定其他bean类型,指的就是在springIOC核心容器中出现的bean对象
<!--配置一个日期类--> <bean id="new" class="java.util.Date"></bean> <!--spring的依赖注入基于set方法--> <!--property标签:根据set方法注入 name标签:用于注入时所调用的set方法名称--> <bean id="accountService2" class="com.itheima.spring.service.impl.AccountServiceImpl2"> <property name="name" value="lisi"></property> <property name="age" value="21"></property> <property name="birthday" ref="new"></property> </bean>public class AccountServiceImpl2 implements AccountService { //如果经常发生变化的数据,并不适合注入的方式 private String name; private Integer age; private Date birthday; public void setName(String name) { this.name = name; } public void setAge(Integer age) { this.age = age; } public void setBirthday(Date birthday) { this.birthday = birthday; } public void saveAccount() { System.out.println("service中的saveAccount方法执行了。。。"+name+","+age+","+birthday); } }优势:创建对象时没有明确限制,可以直接使用默认构造函数 弊端:如果有某个成员必须有值,则获取对象是有可能set方法没有执行-
使用set方法注入集合数据
用于给List结构集合注入的标签:list,array,set
用于给map结构集合注入的标签:map,props
结构相同的的标签可以互换
public class AccountServiceImpl3 implements AccountService { //如果经常发生变化的数据,并不适合注入的方式 private String[] myStrs; private List<String> myList; private Set<String> mySet; private Map<String,String> myMap; private Properties properties; public void saveAccount() { System.out.println(Arrays.toString(myStrs)); System.out.println(myList); System.out.println(mySet); System.out.println(myMap); System.out.println(properties); //省略set方法 }<!--使用set方法注入集合数据--> <bean id="accountService3" class="com.itheima.spring.service.impl.AccountServiceImpl3"> <property name="myStrs"> <array><!--注入数组--> <value>aaa</value> <value>bbb</value> <value>ccc</value> </array> </property> <property name="myList"> <list><!--注入list--> <value>aaa</value> <value>aaa</value> <value>ccc</value> </list> </property> <property name="mySet"> <set><!--注入set--> <value>aaa</value> <value>bbb</value> <value>ccc</value> </set> </property> <property name="myMap"> <map><!--两种方式注入map--> <entry key="1" value="aaa"></entry> <entry key="2" > <value>bbb</value> </entry> <entry key="3" value="ccc"></entry> </map> </property> <property name="properties"> <props> <prop key="1">aaa</prop> <prop key="2">bbb</prop> <prop key="3">ccc</prop> </props> </property>
</bean>
- 使用构造函数提供
- 使用注解提供
* 曾经的xml配置
~~~xml
<bean id="accountService" class="com.itheima.spring.service.impl.AccountServiceImpl" scope="" init-method="" destory-method="">
<property name="" value=""/ref=""></property>
</bean>
~~~
- 用于创建对象的注解
他们的作用就是和在xml配置文件中编写的<bean>标签实现的功能一样。
@Component
作用:用于把当前类对象存入到spring容器中
属性:
value:用于指定bean标签的id,当前不指定value值,默认是当前类名,且首字母小写。
~~~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名称空间和约束-->
<!--扫描包xml配置-->
<context:component-scan base-package="com.itheima"></context:component-scan>
</beans>
~~~
~~~java
//业务层
@Component
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao = new AccountDaoImpl();
public void saveAccount() {
accountDao.saveAccount();
}
}
/**
* 模拟一个表现层,用于调用业务层
*/
public class ControllerTest {
public static void main(String[] args) {
//1.获取核心容器
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
//2.根据id获取Bean对象 两种方式
AccountService accountService = (AccountService) context.getBean("accountServiceImpl");
System.out.println(accountService);
}
}
~~~
@Service:用于业务层
@Controller:用于表现层
@Repository:用于持久层
以上三个注解他们的作用和属性于@Component是一模一样,他们三个是spring框架为我们提供明确的三层使用的注解,使我们的三层对象更加清晰
- 用于注入数据的
他们的作用就是和在xml配置文件中编写的<bean>标签中写一个 <property>的作用一样的
@Autowired:
作用:自动按照类型注入,只要容器中唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功。如果ioc容器中没有任何bean类型和要注入的变量类型匹配,则报错。如果ioc容器中有多个类型匹配时,首先会根据类型查找,然后再根据唯一表示找,如果都不匹配则报错,如果有两个以上匹配也报错。
出现位置:可以是变量,也可以是方法。
细节:在使用注解注入时,set方法就不是必须得了。
@Qualifier:
作用:按照类中注入的基础之上再按照名称注入。它在给类成员注入时不能单独使用,但在给方法参数注入时可以。
属性:
value:用于指定注入bean的id
@Resource:
作用:直接按照Bean的id注入。它可以独立使用。
属性:
name:用于指定bean的。
以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现。另外集合类型的注入只能通过xml来实现。
@Value:
作用:用于注入基本数据类型和String类型的数据。
属性:
value:用于指定数据的值,它可以使用spring中的el表达式的写法,SpEL的写法:${表达式}
- 用于改变作用范围的
他们的作用就是和在xml配置文件中编写的<bean>标签使用scope属性实现的功能是一样的
@Scope:
作用:用于指定bean的作用范围
属性:
value:指定范围的取值,常用取值:singLeton prototype
- 和生命周期相关的
他们的作用就是和在xml配置文件中编写的<bean>标签使用init-method和destory-methods的作用一样
@PreDestroy:
作用:用于指定销毁方法
@PostConstruct
作用:用于指定初始化方法
基于xml实现IOC
配置文件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">
<!--配置service对象-->
<bean id="accountService" class="com.itgyf.service.impl.AccountServiceImpl">
<!--注入dao对象-->
<property name="accountDao" ref="accountDao"></property>
</bean>
<!--配置dao对象-->
<bean id="accountDao" class="com.itgyf.dao.impl.AccountDaoImpl">
<!--注入QueryRunner-->
<property name="runner" ref="runner"></property>
</bean>
<!--配置QueryRunner-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<!--注入数据源-->
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<!--配置数据源-->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--连接数据库的必备信息-->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/my_spring"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
dao层
/**
* 持久层接口
*/
public interface AccountDao {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 查询一个
* @return
*/
Account findAccountById(Integer accountId);
/**
* 保存
* @param account
*/
void saveAccount(Account account);
/**
* 修改
* @param account
*/
void updateAccount(Account account);
/**
* 删除
* @param accountId
*/
void deleteAccount(Integer accountId);
}
/**
* 持久层实现类
*/
public class AccountDaoImpl implements AccountDao {
private QueryRunner runner;
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
public List<Account> findAllAccount() {
try {
return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public Account findAccountById(Integer accountId) {
try {
return runner.query("select * from account where id = ?",new BeanHandler<Account>(Account.class),accountId);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void saveAccount(Account account) {
try {
runner.update("insert into account (name,money) values (?,?)",account.getName(),account.getMoney());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void updateAccount(Account account) {
try {
runner.update("update account set name=? , money=? where id = ?",account.getName(),account.getMoney(),account.getId());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void deleteAccount(Integer accountId) {
try {
runner.update("delete from account where id = ?",accountId);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
service层
/**
* 账户业务层接口
*/
public interface AccountService {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 查询一个
* @return
*/
Account findAccountById(Integer accountId);
/**
* 保存
* @param account
*/
void saveAccount(Account account);
/**
* 修改
* @param account
*/
void updateAccount(Account account);
/**
* 删除
* @param accountId
*/
void deleteAccount(Integer accountId);
}
/**
* 业务层实现类
*/
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
/**
* 查询所有
* @return
*/
public List<Account> findAllAccount() {
List<Account> accounts = accountDao.findAllAccount();
return accounts;
}
/**
* 查询一个
* @param accountId
* @return
*/
public Account findAccountById(Integer accountId) {
Account account = accountDao.findAccountById(accountId);
return account;
}
/**
* 保存
* @param account
*/
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
/**
* 修改
* @param account
*/
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
/**
* 删除
* @param accountId
*/
public void deleteAccount(Integer accountId) {
accountDao.deleteAccount(accountId);
}
}
实体类
/**
* 实体类
* 实现Serializable是实体类的序列化
*/
public class Account implements Serializable {
private Integer id;
private String name;
private float money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getMoney() {
return money;
}
public void setMoney(float money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
测试类
/**
* junit单元测试
*/
public class AccountServiceTest {
//获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//得到业务层对象
AccountService accountService = ac.getBean("accountService", AccountService.class);
//查询所有
@Test
public void findAll() {
List<Account> accounts = accountService.findAllAccount();
for (Account account : accounts) {
System.out.println(account);
}
}
//根据id查询
@Test
public void findById() {
Account account = accountService.findAccountById(3);
System.out.println(account);
}
//保存
@Test
public void save() {
Account account = new Account();
account.setName("test");
account.setMoney(2000f);
accountService.saveAccount(account);
}
//修改
@Test
public void update() {
Account account = new Account();
account.setId(4);
account.setName("test");
account.setMoney(4000f);
accountService.updateAccount(account);
}
//删除
@Test
public void delete() {
accountService.deleteAccount(4);
}
}
基于注解实现IOC
配置文件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在创建容器时需要扫描的包-->
<context:component-scan base-package="com.itgyf"></context:component-scan>
<!--配置QueryRunner-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<!--注入数据源-->
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<!--配置数据源-->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--连接数据库的必备信息-->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/my_spring"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
dao层
/**
* 持久层接口
*/
public interface AccountDao {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 查询一个
* @return
*/
Account findAccountById(Integer accountId);
/**
* 保存
* @param account
*/
void saveAccount(Account account);
/**
* 修改
* @param account
*/
void updateAccount(Account account);
/**
* 删除
* @param accountId
*/
void deleteAccount(Integer accountId);
}
/**
* 基于注解持久层实现类
*/
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
//将对象注入 省去set方法
@Autowired
private QueryRunner runner;
/**
* 保存
* @return
*/
public List<Account> findAllAccount() {
try {
return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public Account findAccountById(Integer accountId) {
try {
return runner.query("select * from account where id = ?",new BeanHandler<Account>(Account.class),accountId);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void saveAccount(Account account) {
try {
runner.update("insert into account (name,money) values (?,?)",account.getName(),account.getMoney());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void updateAccount(Account account) {
try {
runner.update("update account set name=? , money=? where id = ?",account.getName(),account.getMoney(),account.getId());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void deleteAccount(Integer accountId) {
try {
runner.update("delete from account where id = ?",accountId);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
Service层
/**
* 账户业务层接口
*/
public interface AccountService {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 查询一个
* @return
*/
Account findAccountById(Integer accountId);
/**
* 保存
* @param account
*/
void saveAccount(Account account);
/**
* 修改
* @param account
*/
void updateAccount(Account account);
/**
* 删除
* @param accountId
*/
void deleteAccount(Integer accountId);
}
/**
* 基于注解业务层实现类
*/
@Service("accountService")
public class AccountServiceImpl implements AccountService {
//将对象注入 省去set方法
@Autowired
private AccountDao accountDao;
/**
* 查询所有
* @return
*/
public List<Account> findAllAccount() {
List<Account> accounts = accountDao.findAllAccount();
return accounts;
}
/**
* 查询一个
* @param accountId
* @return
*/
public Account findAccountById(Integer accountId) {
Account account = accountDao.findAccountById(accountId);
return account;
}
/**
* 保存
* @param account
*/
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
/**
* 修改
* @param account
*/
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
/**
* 删除
* @param accountId
*/
public void deleteAccount(Integer accountId) {
accountDao.deleteAccount(accountId);
}
}