Spring是一个轻量级的控制反转(IOC)和面向切面(AOP)的容器框架
1:控制反转IOC (inversion of controller)
IOC是一种概念,是把我们程序中类与类之间的依赖关系交给容器去处理,一般有两种方式
A 依赖查找 DL (dependency lookup)
程序提供查找方式,交给容器去查找(回调函数)
B 依赖注入DI (dependency injection)
程序不提供查找方式,提供合适的构造方法或者setter方法,让容器进行注入来解决依赖关系
spring的控制反转就是通过依赖注入来实现
2:什么叫依赖
简单的说,一个类实现某个功能需要依靠另外一个类的帮助来实现
3:基于接口编程的开发方式
当一个方法有多个实现的情况下,我们一般是基于接口的方式进行编程
4:依赖注入:
依赖注入DI:是指一个对象需要另外一个对象时,无需在代码中创建被调用者,而是依赖于外部容器,由外部容器创建后传递给程序,依赖注入是目前为止最好的解耦方式,因为依赖关系是依靠配置文件的方式组织在一起,而不是在程序中的硬编码.
5:Spring的IOC容器通过依赖注入来实现程序之间的依赖关系,达到解耦的作用
A:spring项目环境搭建需要的jar包
* spring-beans-4.2.1.RELEASE.jar > SpringIoC(依赖注入)的基础实现,框架核心jar包,管理bean对象的。
* spring-context-4.2.1.RELEASE.jar > 上下文支持jar包
* spring-core-4.2.1.RELEASE.jar > 框架核心jar包
* spring-expression-4.2.1.RELEASE.jar >SpringEL表达式相关jar包
* hamcrest-core-1.3.jar > junit4.1之后,单元测试拆分成了两个子包,子包1。
* junit-4.11.jar >单元测试拆分成了两个子包,子包2。
* commons-logging.jar >日志的接口包(规范)
* log4j-1.2.17.jar >日志接口的实现包
B:配置文件 applicationContext.xml,加上bean约束
bean的约束在spring-framework-4.2.1.RELEASE\
docs\spring-framework-reference\html\xsd-configuration.html文件查看
6:在spring文件上面实现依赖注入的两种方式
1:在配置文件定义我们的类
<!--相当于我们java代码的 UserService userService = new UserService() -->
<bean id= "userService" class = "com.tz.spring.sysmanage.service.UserServiceForSpring"></bean>
<!--相当于我们java代码的 UserDao userDao = new UserDao() -->
<bean id = "userDao" class = "com.tz.spring.sysmanage.dao.impl.UserDao"></bean>
<!--相当于我们java代码的 UserDaoOther userDaoOther = new UserDaoOther() -->
<bean id= "userDaoOther" class= "com.tz.spring.sysmanage.dao.other.UserDaoOther"></bean>
2:描述依赖关系有两种方式
* 通过构造方法的方式注入:
a:被依赖的类必须有构造方法
b:在配置文件里面来描述依赖关系
<bean id= "userService" class = "com.tz.spring.sysmanage.service.UserServiceForSpring">
<constructor-arg ref="userDaoOther"></constructor-arg>
</bean>
* 通过setter方法注入
a:被依赖的类里面生成依赖类的setter方法
b:在配置文件来描述依赖关系
<bean id= "userService" class = "com.tz.spring.sysmanage.service.UserServiceForSpring">
<property name="userDao" ref="userDaoOther"></property>
</bean>
applicationContext.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">
<!--相当于我们java代码的 UserService userService = new UserService() -->
<!-- 通过构造方法的方式注入
<bean id= "userService"
class = "com.tz.spring.sysmanage.service.UserServiceForSpring">
<constructor-arg ref="userDao"></constructor-arg>
<constructor-arg ref="userDaoOther"></constructor-arg>
</bean> -->
<bean id= "userService"
class = "com.tz.spring.sysmanage.service.UserServiceForSpring">
<property name="userDao" ref="userDaoOther"></property>
</bean>
<!--相当于我们java代码的 UserDao userDao = new UserDao() -->
<bean id = "userDao"
class = "com.tz.spring.sysmanage.dao.impl.UserDao"></bean>
<!--相当于我们java代码的 UserDaoOther userDaoOther = new UserDaoOther() -->
<bean id= "userDaoOther"
class= "com.tz.spring.sysmanage.dao.other.UserDaoOther"></bean>
</beans>
package com.tz.spring.sysmanage.dao;
public interface IUserDao {
public boolean loginUser(String userName,String password);
}
package com.tz.spring.sysmanage.dao.impl;
import com.tz.spring.sysmanage.dao.IUserDao;
public class UserDao implements IUserDao{
public boolean loginUser(String userName, String password) {
System.out.println("这是通过jdbc进行登陆验证的dao方法");
return true;
}
}
package com.tz.spring.sysmanage.dao.other;
import com.tz.spring.sysmanage.dao.IUserDao;
public class UserDaoOther implements IUserDao{
public boolean loginUser(String userName, String password) {
System.out.println("这是通过其他的方式进行登陆验证的dao方法");
return true;
}
}
package com.tz.spring.sysmanage.service;
import com.tz.spring.sysmanage.dao.IUserDao;
import com.tz.spring.sysmanage.dao.impl.UserDao;
//类描述:用于对关于用户登陆,用户增删改查的服务类(service)
public class UserServiceForSpring {
private IUserDao userDao;
/*
//通过构造方法进行注入
public UserServiceForSpring(IUserDao userDao){
this.userDao = userDao;
}*/
//通过setter方法注入
public void setUserDao(IUserDao userDao) {
this.userDao = userDao;
}
/**
* 通过调用与数据库交互的UserDao里面的loginUser方法,判断是否验证成功
* @param userName
* @param password
* @return
*/
public boolean loginUser(String userName,String password){
boolean flag = false;
flag = userDao.loginUser(userName, password);
return flag;
}
}
package com.tz.spring.sysmanage.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tz.spring.sysmanage.service.UserServiceForSpring;
public class SpringInitTest {
//测试容器初始化某个对象
@Test
public void testBeanInit(){
//加载spring配置文件
ApplicationContext ac =
new ClassPathXmlApplicationContext("applicationContext.xml");
//从spring容器中获取bean标签定义的类
UserServiceForSpring userService =
(UserServiceForSpring) ac.getBean("userService");
System.out.println("userService="+userService);
}
//构造方法注入测试
@Test
public void testConstructorDI(){
//加载spring配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//从spring容器中获取bean标签定义的类
UserServiceForSpring userService = (UserServiceForSpring) ac.getBean("userService");
userService.loginUser("aa", "bb");
}
//set方法注入测试
@Test
public void testSetterDI(){
//加载spring配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//从spring容器中获取bean标签定义的类
UserServiceForSpring userService = (UserServiceForSpring) ac.getBean("userService");
userService.loginUser("aa", "bb");
}
}
Spring的IOC容器是通过依赖注入DI(dependency injection)来实现程序之间的依赖关系 ,达到解耦的作用
依赖的方式:
a:基于xml文件配置的注入
* 构造函数注入
* setter方法注入
* 特定接口的注入(用的很少,省略)
a1: 常见pojo类属性的注入
a2: bean的scope属性代表bean对象的作用域 scope = "singleton/prototype"
singleton 仅初始化一次,创建一个实例 A a = new A()
prototype 每一次对bean的访问都会重新创建一个新的实例 A a = new A() A b = new A()
a3: bean的延迟加载
* 在bean标签里面 写入 lazy-init = "false" /lazy-init="true"
* 在beans的头文件里面 写入 default-lazy-init="true" 代表整个配置文件的对象都是延迟加载
a4: spring可以自动的向bean中注入依赖 --自动装配 (autowire)
要实现自动装配主要有两种方式 (setter)
* byName 定义的依赖的bean名称需要与类中引用的名称一致 ,就会匹配依赖关系
<!--byName的自动匹配原则: 在UserAutowireService里面的成员变量名称与配置文件的bean的id进行匹配 -->
* byType 通过定义的依赖bean的类型来进行匹配
总结:建议不要在配置文件里面用自动装配,虽然可以减少配置文件,但是不利于维护
配置文件的读取
//第一种方式 ,单个配置文件的加载
//ClassPathXmlApplicationContext 编译路径
//src目录下的
ApplicationContext ac =
new ClassPathXmlApplicationContext("applicationContext.xml");
UserSetterService userSetterService =
(UserSetterService) ac.getBean("userSetterService");
System.out.println(userSetterService);
//第二种方式 多个文件文件的加载
ApplicationContext ac =
new ClassPathXmlApplicationContext("applicationContext.xml",
"applicationContext-property.xml",
"applicationContext-autowire.xml");
String[] configFiles = new String[]{"applicationContext.xml",
"applicationContext-property.xml",
"applicationContext-autowire.xml"};
ApplicationContext ac =
new ClassPathXmlApplicationContext(configFiles);
//第三种方式: 用约定的方式
ApplicationContext ac =
new ClassPathXmlApplicationContext("applicationContext*.xml");
//第四种方式:读取一个总的配置文件 ,其他配置都被包含在这一个总得配置文件里面
ApplicationContext ac =
new ClassPathXmlApplicationContext("application-all.xml");
application-all.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">
<import resource="applicationContext.xml"/>
<import resource="applicationContext-autowire.xml"/>
<import resource="applicationContext-property.xml"/>
</beans>
//第五种方式:BeanFactory
//用文件系统的路径读取
ApplicationContext ac =
new FileSystemXmlApplicationContext("D:\\Eclipse_WorkSpace\\spring02-IOC-DI\\src\\applicationContext.xml");
UserSetterService userSetterService =
(UserSetterService) ac.getBean("userSetterService");
System.out.println(userSetterService);
<?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的ioc对pojo类(没有实现任何接口,继承任何父类的简单java对象)属性进行依赖注入 -->
<bean id = "user" class = "com.tz.spring.sysmanage.entity.User">
<property name="strValue" value=" I AM STRING "></property>
<property name="intValue" value="1234"></property>
<property name="listValue">
<list>
<value>list1</value>
<value>list2</value>
<value>list3</value>
</list>
</property>
<property name="setValue">
<set>
<value>set1</value>
<value>set2</value>
<value>set3</value>
</set>
</property>
<property name="strArrayValue">
<list>
<value>strArray1</value>
<value>strArray1</value>
<value>strArray1</value>
</list>
</property>
<property name="mapValue">
<map>
<entry key="key1" value= "map1"></entry>
<entry key="key2" value= "map2"></entry>
<entry key="key3" value= "map3"></entry>
</map>
</property>
</bean>
<!-- <bean id = "userOther" class = "com.tz.spring.sysmanage.entity.UserOther"></bean>
-->
<bean id = "userOther" class = "com.tz.spring.sysmanage.entity.UserOther" scope="prototype"></bean>
<bean id = "userAnother" class = "com.tz.spring.sysmanage.entity.UserAnother" lazy-init="true">
</bean>
</beans>
//测试类的命名规范:类名是test结尾,方法是test开头
package com.tz.spring.sysmanage.test;
import static org.hamcrest.CoreMatchers.sameInstance;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tz.spring.sysmanage.entity.User;
import com.tz.spring.sysmanage.entity.UserOther;
public class PropertyDITest {
private ApplicationContext ac;
@Before
public void init(){
ac = new ClassPathXmlApplicationContext("applicationContext-property.xml");
}
//测试pojo的属性注入
@Test
public void testProperty(){
User user = (User)ac.getBean("user");
System.out.println("strValue="+user.getStrValue());
System.out.println("intValue="+user.getIntValue());
System.out.println("listValue="+user.getListValue());
System.out.println("setValue="+user.getSetValue());
System.out.println("strArrayValue="+user.getStrArrayValue());
System.out.println("mapValue="+user.getMapValue());
}
//测试scope属性 singleton
@Test
public void testBeanScopeSingleton(){
UserOther other1 = (UserOther) ac.getBean("userOther");
UserOther other2 = (UserOther) ac.getBean("userOther");
System.out.println(other1.toString());
System.out.println(other2.toString());
System.out.println(other1==other2);
}
//测试scope属性 ProtoType
@Test
public void testBeanScopeProtoType(){
UserOther other1 = (UserOther) ac.getBean("userOther");
UserOther other2 = (UserOther) ac.getBean("userOther");
System.out.println(other1.toString());
System.out.println(other2.toString());
System.out.println(other1==other2);
}
//测试bean的延迟加载
//测试思路:故意在xml配置文件里面应用一个不存在的类
@Test
public void testBeanLazyInit(){
System.out.println("---------容器已经启动-----------");
ac.getBean("userAnother");
}
}
基于注解的注入 :就是用注解标签的方式来替换掉我们xml配置文件里面bean的注册和依赖关系的描述
a:首先我们回顾实现IOC(控制反转) ,进行依赖注入需要做到的两件事情
1:注册类 2:描述依赖关系
b:注解的 实现步骤
* 加入jar包 spring-aop-4.2.1.RELEASE.jar > 这个jar文件包含在应用中使用Spring的AOP特性时所需的类
* 加入context约束
* 在appliactionContext.xml配置里面定义扫描需要用到的直接的包路径
<context:component-scan base-package="com.tz.spring.annotation"></context:component-scan>
* 在需要注解的bean对象前面加入注解标识符
@Component 说明当前类是一个组件 ,相当于在配置文件里面<bean id = "" class= "">
定义component注解还有三种方式
@Repository :这个注解主要是声明dao的类组件
@Service :这个注解主要是声明service服务类的
@Controller :这个注解主要是声明控制类 (springmvc/struts2 action/controller)
* 用注解表示符autowire来声明依赖关系
@Resource java的注解 ,他默认是以byName方式注入,byName找不到的话,再用byType去匹配
@Autowired spring的注解,默认是以byType注入,--如果有多个实现类,他再用byName的方式去匹配
@Autowired @Qualifier spring的注解,两个一起用,指定用byName的方式进行匹配
注意: 注解不需要设置setter方法 ,但是我们还是一般写上
因为当我们在配置文件里面配置了bean的时候 ,而且通过配置文件描述了依赖关系,会优先使用配置,如果没有setter方法,会报异常。
package com.tz.spring.annotation.dao.other;
import org.springframework.stereotype.Repository;
import com.tz.spring.annotation.dao.IUserAnnotationDao;
@Repository("userAnnotationDaoOther")
public class UserAnnotationDaoOther implements IUserAnnotationDao{
public boolean loginUser(String userName, String password) {
System.out.println("这是通过其他方式来进行登陆验证");
return true;
}
}
package com.tz.spring.annotation.service;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.tz.spring.annotation.dao.IUserAnnotationDao;
//说明当前类是一个组件 ,相当于在配置文件里面<bean id = "userAnnotationService" class= "">
//@Component("userAnnotationService")
@Service("userAnnotationService") //
@Scope("prototype") //默认是singleton
public class UserAnnotationService {
//@Autowired //默认是用byType的方式注入 ,如果遇到多个实现类,则用byName方式匹配
//@Qualifier("userAnnotationDao") //指定需要匹配的依赖类的名称
@Resource //他是java的注解,默认是byName的方式注入
private IUserAnnotationDao userAnnotationDaoOther;
public void setUserAnnotationDaoOther(IUserAnnotationDao userAnnotationDaoOther) {
this.userAnnotationDaoOther = userAnnotationDaoOther;
}
public boolean loginUser(String userName,String password){
boolean flag = false;
flag = userAnnotationDaoOther.loginUser(userName, password);
return flag;
}
}
测试类
package com.tz.spring.annotation.test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tz.spring.annotation.service.UserAnnotationService;
public class DIAnnotationTest {
private ApplicationContext ac;
@Before
public void init(){
ac = new ClassPathXmlApplicationContext("applicationContext.xml");
}
//测试注解来实现依赖注入
@Test
public void testUserAnnotationService(){
UserAnnotationService userAnnotationService =
(UserAnnotationService) ac.getBean("userAnnotationService");
UserAnnotationService userAnnotationService1 =
(UserAnnotationService) ac.getBean("userAnnotationService");
System.out.println(userAnnotationService == userAnnotationService1);
userAnnotationService.loginUser("aaa", "bbbb");
}
}
Spring IOC 总结
Spring 的IOC(控制反转)是通过依赖注入(dependency injection)来实现的
优点 :
* 大量减少了对象的创建和管理 ,使代码层次更加清晰
* Spring 的IOC容器是一个轻量级的容器 ,没有侵入性(不依赖容器的API) ,不需要实现一些特殊接口
这是一个合理设计的基本要求
* 鼓励我们面向接口编程
* 减少了代码的耦合,将耦合的部分推到了配置文件中 ,如果他们的关系发生了改变,只需要修改配置文件
* 提供了aop声明式的服务能力
Spring 核心容器之一IOC 的一大应用
springJdbcTemplate 实现 一个表的简单的增删改查
1:建表 student (id,name,age)
2:服务层的接口和实现类以及dao层的接口和实现类
3:利用springIOC 实现服务类和Dao类的依赖
4:注册类似于DbUtil的管理数据库连接的类
注入数据库连接的四要素
* 引入jar包
spring-jdbc-4.2.1.RELEASE.jar > 这个jar 文件包含对Spring 对JDBC 数据访问进行封装的所有类。
spring-tx-4.2.1.RELEASE.jar > 为JDBC、Hibernate、JDO、JPA、Beans等提供的一致的声明式和编程式事务管理支持。
* oracle和mysql的驱动包 .
mysql-connector-java-5.0.8-bin.jar
ojdbc14.jar
* 注册数据源,注入数据库四要素
<!--注册spring自带的管理数据库连接的数据源 -->
<bean id= "dataSource"
class= "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/springjdbc_test"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
5:注册jdbctemplate,依赖于datasource
<!--注册springjdbc查询模板 模板依赖数据源 -->
<bean id= "jdbcTemplate" class = "org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref = "dataSource"></property>
</bean>
6:描述dao类与jdbcTemplate的依赖关系
<!--注册studentDao -->
<bean id = "studentDao"
class = "com.tz.spring.sysmanage.dao.impl.StudentDao">
<property name="jdbcTemplate" ref = "jdbcTemplate"></property>
</bean>
7:学生表的增删改查操作
8:用注解来实现学生表的增删改查
9:在dao类里面也可以继承JdbcDaoSupport的方式来完成增删改查操作
注意:在dao类里面可以跳过jdbcTemplate的注入,直接注入datasource
10:利用properties的配置文件将数据库连接的四要素信息注入到数据源当中
<!--注册spring自带的管理数据库连接的数据源 -->
<bean id= "dataSource"
class= "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--从propertes配置加载数据库信息
1:制作一个jdbc.properties
2:让spring加载jdbc.properties
3:将properties的信息注入到数据源当中
让spring加载jdbc.properties 有如下两种方式
-->
<bean class = "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties"></property>
</bean>
<context:property-placeholder location = "classpath:jdbc.properties"/>
11:配置c3p0数据源
* 引入c3p0连接池的jar包
* 在applicationContext.xml配置文件里面注册c3p0连接池
<!--注册c3p0的连接池 -->
<bean id= "dataSource"
class= "com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
12:配置dbcp数据源
* 引入dbcp数据源需要的jar包
commons-dbcp-1.4.jar
commons-pool-1.6.jar
* 在appliactionContext.xml配置文件里面注册dbcp连接池
<!--注册dbcp的连接池 -->
<bean id= "dataSource"
class= "org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<?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"
>
<!--注册studentService 描述依赖关系-->
<!-- <bean id = "studentService"
class = "com.tz.spring.sysmanage.service.impl.StudentService">
<property name="studentDao" ref = "studentDao"></property>
</bean> -->
<!--用另外一种方式实现增删改查 extends JdbcDaoSupport -->
<bean id = "studentService"
class = "com.tz.spring.sysmanage.service.impl.StudentService">
<property name="studentDao" ref = "studentDaoOther"></property>
</bean>
<!--注册studentDao -->
<bean id = "studentDao"
class = "com.tz.spring.sysmanage.dao.impl.StudentDao">
<property name="jdbcTemplate" ref = "jdbcTemplate"></property>
</bean>
<!--注册studentDaoOther 当我们在dao类里面继承JdbcDaoSupport实现增删改查的时候,可以直接注入dataSource -->
<bean id = "studentDaoOther"
class = "com.tz.spring.sysmanage.dao.impl.StudentDaoOther">
<property name="dataSource" ref = "dataSource"></property>
</bean>
<!--注册springjdbc查询模板 模板依赖数据源 -->
<bean id= "jdbcTemplate" class = "org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref = "dataSource"></property>
</bean>
<!--注册spring自带的管理数据库连接的数据源 -->
<!-- <bean id= "dataSource"
class= "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean> -->
<!--注册c3p0的连接池 -->
<!-- <bean id= "dataSource"
class= "com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean> -->
<!--注册dbcp的连接池 -->
<bean id= "dataSource"
class= "org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--从propertes配置加载数据库信息
1:制作一个jdbc.properties
2:让spring加载jdbc.properties
3:讲properties的信息注入到数据源当中
让spring加载jdbc.properties 有如下两种方式
-->
<!-- <bean class = "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties"></property>
</bean> -->
<context:property-placeholder location = "classpath:jdbc.properties"/>
</beans>
jdbc.properties文件:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/springjdbc_test
jdbc.user=root
jdbc.password=123456
package com.tz.spring.sysmanage.dao.impl;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import com.tz.spring.sysmanage.dao.IStudentDao;
import com.tz.spring.sysmanage.entity.Student;
public class StudentDao implements IStudentDao{
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public boolean addStudent(Student student) {
boolean flag = false;
String addSql = "INSERT INTO STUDENT(NAME,AGE)VALUES(?,?) ";
int rows = this.jdbcTemplate.update(addSql, student.getName(),student.getAge());
if(rows>0){
flag = true;
}
return flag;
}
@Override
public boolean delStudent(Integer studentId) {
boolean flag = false;
String delSql = "DELETE FROM STUDENT WHERE ID = ?";
int rows = this.jdbcTemplate.update(delSql,studentId);
if(rows>0){
flag = true;
}
return flag;
}
@Override
public boolean updateStudent(Student student) {
boolean flag = false;
String updateSql = "UPDATE STUDENT SET NAME= ? ,AGE = ? WHERE ID = ?";
int rows = this.jdbcTemplate.update(updateSql,student.getName(),student.getAge(),student.getId());
if(rows>0){
flag = true;
}
return flag;
}
@Override
public List<Student> getStudentList() {
String querySql = "SELECT ID,NAME,AGE FROM STUDENT ";
//第一种方式 用接口的匿名内部类实现
/*return this.jdbcTemplate.query(querySql, new RowMapper<Student>(){
@Override
public Student mapRow(ResultSet resultSet, int rowNum) throws SQLException {
Student stu = new Student();
stu.setId(resultSet.getInt("ID"));
stu.setName(resultSet.getString("NAME"));
stu.setAge(resultSet.getInt("AGE"));
return stu;
}
});*/
//第二种方式,直接将行结果集映射到实体类
return this.jdbcTemplate.query(querySql,
new BeanPropertyRowMapper<Student>(Student.class));
}
@Override
public List<Map<String, Object>> getStudentMap() {
return this.jdbcTemplate.queryForList("SELECT ID,NAME,AGE FROM STUDENT");
}
}
注解
applicationContext-annotation.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"
>
<!--开启扫描 -->
<context:component-scan base-package="com.tz.spring.annotation.* ">
</context:component-scan>
<!--注册springjdbc查询模板 模板依赖数据源 -->
<bean id= "jdbcTemplate" class = "org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref = "dataSource"></property>
</bean>
<!--注册spring自带的管理数据库连接的数据源 -->
<bean id= "dataSource"
class= "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/springjdbc_test"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
</beans>
package com.tz.spring.annotation.dao;
import java.util.List;
import java.util.Map;
import com.tz.spring.sysmanage.entity.Student;
/**
* 用于对外提供学生dao类的增删改查接口
* @author Administrator
*
*/
public interface IStudentAnnotationDao {
public boolean addStudent(Student student);
public boolean delStudent(Integer studentId);
public boolean updateStudent(Student student);
public List<Student> getStudentList();
public List<Map<String,Object>> getStudentMap();
}
package com.tz.spring.annotation.dao.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.tz.spring.annotation.dao.IStudentAnnotationDao;
import com.tz.spring.sysmanage.entity.Student;
@Repository("studentAnnotationDao")
public class StudentAnnotationDao implements IStudentAnnotationDao{
@Autowired
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public boolean addStudent(Student student) {
boolean flag = false;
String addSql = "INSERT INTO STUDENT(NAME,AGE)VALUES(?,?) ";
int rows = this.jdbcTemplate.update(addSql, student.getName(),student.getAge());
if(rows>0){
flag = true;
}
return flag;
}
@Override
public boolean delStudent(Integer studentId) {
boolean flag = false;
String delSql = "DELETE FROM STUDENT WHERE ID = ?";
int rows = this.jdbcTemplate.update(delSql,studentId);
if(rows>0){
flag = true;
}
return flag;
}
@Override
public boolean updateStudent(Student student) {
boolean flag = false;
String updateSql = "UPDATE STUDENT SET NAME= ? ,AGE = ? WHERE ID = ?";
int rows = this.jdbcTemplate.update(updateSql,student.getName(),student.getAge(),student.getId());
if(rows>0){
flag = true;
}
return flag;
}
@Override
public List<Student> getStudentList() {
String querySql = "SELECT ID,NAME,AGE FROM STUDENT ";
//第一种方式 用接口的匿名内部类实现
/*return this.jdbcTemplate.query(querySql, new RowMapper<Student>(){
@Override
public Student mapRow(ResultSet resultSet, int rowNum) throws SQLException {
Student stu = new Student();
stu.setId(resultSet.getInt("ID"));
stu.setName(resultSet.getString("NAME"));
stu.setAge(resultSet.getInt("AGE"));
return stu;
}
});*/
//第二种方式,直接将行结果集映射到实体类
return this.jdbcTemplate.query(querySql,
new BeanPropertyRowMapper<Student>(Student.class));
}
@Override
public List<Map<String, Object>> getStudentMap() {
return this.jdbcTemplate.queryForList("SELECT ID,NAME,AGE FROM STUDENT");
}
}
package com.tz.spring.annotation.service;
import java.util.List;
import java.util.Map;
import com.tz.spring.sysmanage.entity.Student;
/**
* 用于对外提供学生服务类的增删改查接口
* @author Administrator
*
*/
public interface IStudentAnnotationService {
public boolean addStudent(Student student);
public boolean delStudent(Integer studentId);
public boolean updateStudent(Student student);
public List<Student> getStudentList();
public List<Map<String,Object>> getStudentMap();
}
package com.tz.spring.annotation.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tz.spring.annotation.dao.IStudentAnnotationDao;
import com.tz.spring.annotation.service.IStudentAnnotationService;
import com.tz.spring.sysmanage.entity.Student;
/**
* 用于对外提供学生服务类的增删改查实现
* @author Administrator
*
*/
@Service("studentAnnotationService")
public class StudentAnnotationService implements IStudentAnnotationService{
@Autowired
private IStudentAnnotationDao studentAnnotationDao;
public void setStudentAnnotationDao(IStudentAnnotationDao studentAnnotationDao) {
this.studentAnnotationDao = studentAnnotationDao;
}
@Override
public boolean addStudent(Student student) {
return this.studentAnnotationDao.addStudent(student);
}
@Override
public boolean delStudent(Integer studentId) {
return this.studentAnnotationDao.delStudent(studentId);
}
@Override
public boolean updateStudent(Student student) {
return this.studentAnnotationDao.updateStudent(student);
}
@Override
public List<Student> getStudentList() {
return this.studentAnnotationDao.getStudentList();
}
@Override
public List<Map<String, Object>> getStudentMap() {
return this.studentAnnotationDao.getStudentMap();
}
}
<?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"
>
<!--注册studentService 描述依赖关系-->
<bean id = "studentService"
class = "com.tz.spring.sysmanage.service.impl.StudentService">
<property name="studentDao" ref = "studentDao"></property>
</bean>
<!--注册studentDao -->
<bean id = "studentDao"
class = "com.tz.spring.sysmanage.dao.impl.StudentDao">
<property name="jdbcTemplate" ref = "jdbcTemplate"></property>
</bean>
<!--注册springjdbc查询模板 模板依赖数据源 -->
<bean id= "jdbcTemplate" class = "org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref = "dataSource"></property>
</bean>
<!--注册spring自带的管理数据库连接的数据源 -->
<bean id= "dataSource"
class= "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/springjdbc_test"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
</beans>