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();
}
}
原文
https://segmentfault.com/a/1190000022124614
本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » 说说我的Spring入门