Spring的简单概述以及开发步骤
Spring的优势
- 方便解耦,简化开发
- AOP编程的支持
- 声明式事务的支持
- 方便程序的测试
- 方便集成各种优秀框架
- 降低JavaEE API的使用难度
- Java源码的经典学习范例
Spring的体系结构:可以观看 http://c.biancheng.net/spring/module.html
开发步骤
一, 导入spring坐标
org.springframework
spring-beans
5.3.12
org.springframework
spring-core
5.3.12
org.springframework
spring-context
5.0.5.RELEASE
二, 编写Dao接口和实现类()
三, 创建Spring核心配置文件
Spring的核心配置文件一般命名为applicationContext.xml
在新建下面的XML Configuration File下选Spring Config
四, 在spring配置文件中配置Dao接口的实现类
例在dao层下写一个UserDao的接口,然后再impl下写UserDao的实现类UserDaoImpl后
在bean的配置文件下导入
五, 使用spring的API获得bean实例
使用ClassPathXMLApplicationContext来读取Spring的配置文件,再去使用getBean获取类型
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = app.getBean(UserService.class);//这个里有三种写法
app.getBean(UserService.class)
app.getBean("userDao",UserService.class)//这里的userDao 是配置文件bean下的id名
app.getBean("userDao")//配置文件bean下的id名
例如我们在编写dao层是按照以往惯例需要在dao层写上接口,并在impl中写上接口的实现类,而当我们需要使用它们时XxxDao xxDao=new XxxDaoImpl();
在Spring中我们需要在spring容器里面(bean.xml或applicationContext.xml)通过反射创建Bean对象,再返回对象
Spring的配置文件:
其中的id是唯一标识。