spring是当前最流行的java开发框架,它的控制反转功能可以对程序进行解耦。下面来演示一个最简单的例子
首先文件的工程目录如下,
public class AccountDaoImpl implements IAccountDao {
public void saveAccount(){
System.out.println("保存了账户");
}
}
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao = new AccountDaoImpl();
public void saveAccount(){
accountDao.saveAccount();
}
}
原本我们要想使用这两个实现类,必须要new出它们。借助spring后,我们不必直接创建它们,我们把创建它们的功能交给了spring,调用spring中的方法我们也能创建它们了。
要实现spring的控制功能,我们需要把这两个类交给spring的容器,这是通过下面的配置文件bean.xml完成的。
其中前两个标签为版本信息。在bean标签中指定要交给spring管理的类的全路径以及为其所取的id,以后spring通过id便可该类对象。
<?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="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"></bean>
</beans>
这是测试类:先获取容器对象,再在容器对象中通过id获取类对象
public class Client {
public static void main(String[] args) {
//1 获取核心容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2 根据id获取Bean对象
IAccountService as = (IAccountService)ac.getBean("accountService") ;
IAccountDao adao = ac.getBean("accountDao",IAccountDao.class);
System.out.println(as);
System.out.println(adao);
as.saveAccount();
adao.saveAccount();
}
}