- Spring

>> Spring 基础

~ Spring概念

1、Spring是开源的轻量级的框架;
2、Spring核心主要有两部分:
(1)AOP面向切面编程,扩展功能不是修改源代码实现;
(2)IoC控制反转
比如有一个类,在类里面有非静态的方法,调用类里面的方法,原始操作是需要先创建类的对象,然后使用对象调用方法, 创建类对象的过程,需要new出来对象;
控制反转:把对象的创建交给spring进行管理,而不是通过new的方式实现;(交给spring配置创建类对象)
3、spring是一站式框架: 在JavaEE三层结构中,每一层都提供不同的解决技术:

  • Web层:SpringMVC;
  • Service层:Spring的IoC;
  • Dao层:Spring的JdbcTemplate;

~ Spring的IoC操作

1、把对象的创建交给spring进行管理;
2、IoC的操作有两种方式:
(1)通过IoC的配置文件的方式:
(2)通过IoC的注解方式:

~ IoC底层原理

IoC底层原理使用的技术:
(1)xml配置文件;
(2)dom4j解析xml文件;
(3)工厂的设计模式;
(4)java的反射机制;
因为工厂类里面是通过Java反射技术创建的对象实例,而不是通过new创建对象的,所以servlet和Factory类之间的耦合度降低了;
在这里插入图片描述

~ 入门案例

  • 第一步:导入jar包:
    在这里插入图片描述
  • 第二步:创建对象类,在类里面创建方法;
  • 第三步:创建spring配置文件applicationContext.xml(官方建议的名称),配置创建类对象:
    <bean id="user" class="cn.itcast.ioc.User"></bean>
  • 第四步:写代码测试对象创建:
    在这里插入图片描述

~ Spring的Bean管理(xml方式)

xml方式管理Bean:在spring里面通过配置文件创建对象:

Bean实例化实现的方式有三种:

  • (1)使用类的无参构造器: 入门程序中使用的就是(重点)
    注意:若类里面没有无参构造器,会出现异常:No default constructor found;所以创建类的时候,若添加了带参构造函数,需要同时加上无参构造函数;
    在这里插入图片描述
  • (2)使用静态工厂创建: 创建工厂类,在类里面创建静态方法,返回类的对象;在配置文件里直接创建工厂对象,servlet使用对象时,直接获取工厂类的Bean,赋值给类对象即可;(了解)
    在这里插入图片描述
  • (3)使用实例工厂创建: 创建工厂类,在类里面创建普通方法,返回类的对象;(了解)
    在这里插入图片描述

~ Bean标签常用属性

<bean id="user" class="cn.itcast.User" name="不用了" scope="singleton"></bean>
(1)id:创建的对象的唯一标识,通过id值获取对象:User1 user1 = (User1) context.getBean("user1");(id=user1);id属性值不能包含特殊字符;
(2)class:需要创建对象Bean的类的全限定名;
(3)name:(一般不使用),功能与id一样,到那时属性值可以包含特殊字符(# _);
(4)scope

  • singleton:默认值,单例;
  • prototype:多实例;
  • request:创建对象,把对象放到request域;
  • session:创建对象,把对象放到session域;
  • globalSession:创建对象,把对象放到globalSession域;

~ 属性注入

1、属性注入:创建对象的时候,向类的属性设置值;
2、java代码实现属性注入的方式有3种:
(1)使用set方法注入
(2)使用有参构造函数注入
(3)使用接口注入;(了解)
在这里插入图片描述
3、在spring框架里面,支持前两种方式:
(1)使用set方法注入属性(重点);
在这里插入图片描述
(2)使用有参构造函数注入属性;
在这里插入图片描述

~ 注入对象类型的属性

1、应用场景: Action中创建service对象,service里面又需要创建dao对象,可以把new的操作交给spring操作;

2、实现过程:
(1)创建service类和dao类:
(2)在service类里面定义dao类型的属性;
(3)生成dao类型的属性的set方法;
(4)在service里面得到dao对象,通过dao对象调用dao对象的方法;
(5)在配置文件中注入对象类型属性;
在这里插入图片描述

~ p名称空间注入

在xml文件头引入p名称空间引用:xmlns:p="http://www.springframework.org/schema/p"
在这里插入图片描述

~ 注入复杂类型属性

(1)数组
(2)list集合
(3)map集合
(4)properties
在这里插入图片描述

~ IoC和DI区别

IoC:控制反转,把对象的创建交给spring进行配置;
DI:依赖注入,向类里面的属性中赋值;
关系:依赖注入不能单独存在,需要在IoC基础之上完成操作;

~ Spring整合web项目原理

1、加载spring配置文件:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
在controller里面可以通过new的方式实现,但是每次都new出来一个新的对象,效率很低(多实例);

2、实现思想: 把加载配置文件和创建对象的过程,在服务器启动的时候完成;

3、实现原理: ServletContext对象+监听器
(1)在服务器启动的时候,为每个项目创建一个ServletContext对象;(唯一的,只有一个)
(2)在ServletContext对象创建的时候,使用监听器可以监听到ServletContext对象在什么时候创建;
(3)使用监听器监听到ServletContext对象创建的时候,加载spring配置文件,把配置文件配置的对象创建出来;
(4)把创建出来的对象,放到ServletContext域对象里面(使用setAttribute方法)
(5)获取对象的时候,使用getAttribute方法,到ServletContext对象域中得到;
在这里插入图片描述


>> Spring的Bean管理(注解方式)

~ 注解概念

1、代码里面的特殊标记,使用注解可以完成功能;
2、注解格式:@注解名称(属性名称=属性值);【属性名称是value时,可省略,直接写"属性值"】
3、注解可以使用在 类、方法、属性 上面;

~ 注解开发准备

1、引入jar包:
在这里插入图片描述
2、在spring配置文件中引入约束xmlns:context="http://www.springframework.org/schema/context"

~ 注解注入类 - 创建对象

1、创建类,在需要创建对象的类上面使用注解实现:
在这里插入图片描述
2、在spring的配置文件中开启注解扫描:
在这里插入图片描述

~ 创建对象有四个注解

Spring中提供了四个注解,功能目前来讲是一样的,都用来创建对象;后三个注解是为了让标注类本身的用途更清晰;

  • @Component:基础注解,其他三个是其衍生出来的;
  • @Controller:web层
  • @Service:业务层
  • @Repository:持久层

~ 注解注入属性

1、需求: 创建service、dao类,在service类中定义dao属性,在controller中可以通过service对象获取到dao对象;
2、在UserDao类上使用@Component注解创建UserDao对象;
3、在UserService类上使用@Service注解创建UserService对象;
4、在UserService类里面的UserDao属性上使用@AutoWired或@Resource注解注入属性值;
在这里插入图片描述

属性注入的注解有两个:

  • @Autowired:自动根据类名找到类名对应的对象,跟注解属性中定义的名称无关;
  • @Resource(name=value):name属性的值是注解创建对象的value值;常用这个注解,因为可以指定要注入的具体对象;

~ 配置文件和注解混合使用

1、使用配置文件完成对象的创建;
2、使用注解完成对象属性的注入;
在这里插入图片描述


>> AOP

~ AOP概念

AOP:面向切面编程,扩展功能不修改源代码,而是通过配置实现;
AOP采用横向抽取机制,取代了传统的纵向继承体系重复性代码;

~ AOP原理

在这里插入图片描述

~ AOP操作术语

(1)Joinpoint(连接点):类里面可以被增强(扩展功能)的方法,这些方法称为连接点;
Eg:User类里面的add方法、delete方法、update方法、findAll方法;
(2)Pointcut(切入点):在类里面可以有很多方法被增强,实际增强的方法称为切入点;
Eg:实际操作中,只增强了类里面的add方法和update方法,这两个方法称为切入点;
(3)Advice(通知/增强):实际增强的逻辑,称为增强;
Eg:在User类中的add方法,扩展日志功能,这个日志功能称为增强;

  • 前置通知:逻辑在方法执行之前执行;
  • 后置通知:逻辑在方法执行之后执行;
  • 最终通知:在后置之后执行;
  • 环绕通知:逻辑在在方法执行之前和之后执行;例如:记录方法执行的时间;
  • 异常通知:逻辑在方法执行出现异常时执行;

(4)Aspect(切面):把增强应用到具体的方法上,这个过程称为切面;也就是 把增强用到切入点的过程;
(5)Introduction(引介):在不修改类代码的情况下,动态的添加一些方法或属性;
(6)Target(目标):要增强的类;Eg:User类
(7)Weaving(织入):把增强应用到目标的过程;(把advice应用到target的过程)
(8)Proxy(代理):一个类被AOP织入增强后,就产生一个结果代理类;

~ AOP 操作

1、在spring里面进行aop操作,使用aspectj实现:
(1)aspectj不是spring的一部分,和spring一起使用进行aop操作;
(2)spring2.0之后新增了对aspectj的支持;

2、使用aspectj实现aop有两种方式:
(1)基于aspectj的xml配置的方式;
(2)基于aspectj的注解的方式;

3、aop操作环境准备:
(1)所需jar包:
在这里插入图片描述
(2)在spring配置文件里导入aop约束;
在这里插入图片描述

4、使用表达式配置切入点:
(1)切入点:实际增强的方法;
(2)常用表达式execution(<访问修饰符>空格<返回类型的全限定名><方法名>(<参数>)<异常>)

  • execution(* cn.itcast.g_aop.BaseBook.test(..)):指定类里面的test方法;
  • execution(* cn.itcast.g_aop.BaseBook.*(..)):指定类里面的所有方法;
  • execution(* *.*(..)):匹配所有包下所有类的所有方法;
  • execution(* save*(..)):匹配所有save开头的方法;

5、基于aspectj的aop操作 - xml配置方式:
在这里插入图片描述

6、基于aspectj的aop操作 - 基于注解的方式:
在这里插入图片描述


>> JdbcTemplate实现crud操作

~ 环境准备

1、所需jar包:JdbcTemplate + c3p0 + mysql数据库驱动包
在这里插入图片描述

2、数据库 + 数据表 + 用户类:spring + user + UserInfo
在这里插入图片描述

~ 原始Jdbc代码实现对数据的操作

在这里插入图片描述

~ 添加操作

在这里插入图片描述

~ 删除操作

在这里插入图片描述

~ 更新操作

在这里插入图片描述

~ 查询操作

JdbcTemplate实现查询操作,有RowMapper接口,但针对这个接口没有提供实现类,得到不同类型的数据需要自己进行数据的封装;

(1)查询返回某一个值:查询表中有多少条记录:
在这里插入图片描述

RowMapper接口实现类:
在这里插入图片描述

(2)查询返回对象:
在这里插入图片描述

(3)查询返回list集合:
在这里插入图片描述

~ Spring配置c3p0连接池和dao使用jdbcTemplate

(1)在spring配置文件中配置连接池:
(2)在JdbcTemplate模板对象里面注入DataSource:
(3)创建JdbcTemplate模板对象,把模板对象注入到dao里面:
(4)创建Service和Dao,在spring配置文件中配置service和dao对象,在service中注入dao对象:
在这里插入图片描述


>> Spring 的事务管理

~ 事务的概念

1、什么是事务
事务 是应用程序中一系列严密的操作,所有操作必须成功完成,否则在每个操作中所作的所有更改都会被撤消;也就是事务具有原子性,一个事务中的一系列的操作要么全部成功,要么一个都不做;

事务的结束有两种,当事务中的所以步骤全部成功执行时,事务提交;如果其中一个步骤失败,将发生回滚操作,撤消撤消之前到事务开始时的所有操作;

2、事务的特性:原子性( Atomicity )、一致性( Consistency )、隔离性( Isolation )和持续性( Durability )

  • 原子性:事务是数据库的逻辑工作单位,事务中包含的各操作要么都做,要么都不做;
  • 一致性:事务执行的结果必须是使数据库从一个一致性状态变到另一个一致性状态;因此当数据库只包含成功事务提交的结果时,就说数据库处于一致性状态;如果数据库系统 运行中发生故障,有些事务尚未完成就被迫中断,这些未完成事务对数据库所做的修改有一部分已写入物理数据库,这时数据库就处于一种不正确的状态,或者说是 不一致的状态
  • 隔离性:一个事务的执行不能其它事务干扰;即一个事务内部的操作及使用的数据对其它并发事务是隔离的,并发执行的各个事务之间不能互相干扰;
  • 持续性:也称永久性,指一个事务一旦提交,它对数据库中的数据的改变就应该是永久性的;接下来的其它操作或故障不应该对其执行结果有任何影响;

3、不考虑隔离性,会产生读的问题:

4、解决读问题:设置隔离级别;

~ Spring 事务管理API

1、spring事务管理有两种方式:

  • 编程式事务管理(一般不用)
  • 声明式事务管理
  • (1)基于xml配置文件实现
  • (2)基于注解实现

2、spring事务管理的API:
接口:PlatFormTransactionManager(事务管理器)

spring针对不同的dao层框架,提供了不同的实现类:

  • 使用Spring Jdbc或MyBatis进行持久化:
    org.springframework.jdbc.datasource.DataSourceTransactionManager
  • 使用Hibernate5.0进行持久化数据时:
    org.springframework.orm.hibernate5.HibernateTransactionManager

~ 案例 - 转账

1、环境搭建:创建数据库表,添加数据;
在这里插入图片描述

2、需求: 墨遥 转账 1000给 墨晨:墨遥少1000,墨晨多1000;

3、创建service和dao类,完成对象创建、注入,及service层的业务逻辑的编写操作:

4、产生问题:如果墨遥少了1000之后,代码出现异常,墨晨不会多1000,钱丢失了;
Eg:在Service层调用Dao层的两个方法之间添加异常代码:int i = 10/0;
解决:添加事务解决,出现异常之后进行事务的回滚操作;
在这里插入图片描述

~ 声明式事务管理 - xml配置方式

在这里插入图片描述

~ 声明式事务管理 - 注解方式

在这里插入图片描述


>> 代码

~ 项目结构

在这里插入图片描述

~ jar包

在这里插入图片描述

~ 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" 
	   xmlns:p="http://www.springframework.org/schema/p"
	   xmlns:aop="http://www.springframework.org/schema/aop"
	   xmlns:tx="http://www.springframework.org/schema/tx"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xsi:schemaLocation="http://www.springframework.org/schema/aop 
         				   http://www.springframework.org/schema/aop/spring-aop.xsd
         				   http://www.springframework.org/schema/beans 
				           http://www.springframework.org/schema/beans/spring-beans.xsd 
         				   http://www.springframework.org/schema/tx 
				           http://www.springframework.org/schema/tx/spring-tx.xsd 
				           http://www.springframework.org/schema/context 
				           http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- 使用类的无参构造器创建对象 -->
	<bean id="user1" class="cn.itcast.a_bean.User1"></bean>
	
	<!-- 使用静态工厂创建对象 -->
	<bean id="user2" class="cn.itcast.a_bean.User2Factory" factory-method="getUser2"></bean>

	<!-- 使用实例工厂创建工厂类的对象 -->
	<bean id="user3Factory" class="cn.itcast.a_bean.User3Factory" ></bean>
	<!-- 创建bean,引用工厂的Bean -->
	<bean id="user3" factory-bean="user3Factory" factory-method="getUser3"></bean>

	<!-- (1)使用set方法注入属性(重点); -->
	<bean id="propertyDemo1" class="cn.itcast.b_peoperty.PropertyDemo1">
		<property name="username" value="set方法注入"></property>
	</bean>
	<!-- p名称空间注入 -->
	<bean id="propertyDemo1p" class="cn.itcast.b_peoperty.PropertyDemo1" p:username="set方法注入p"></bean>

	<!-- (2)使用有参构造函数注入属性; -->
	<bean id="propertyDemo2" class="cn.itcast.b_peoperty.PropertyDemo2">
		<constructor-arg name="username" value="有参构造注入"></constructor-arg>
	</bean>
	
	<!-- 注入对象类型属性:配置service、dao对象  -->
	<bean id="userDao" class="cn.itcast.c_objectproperty.UserDao"></bean>
	<bean id="userService" class="cn.itcast.c_objectproperty.UserService">
	    <!-- 通过property标签在service Bean中注入dao对象属性;
	    	 name:service类中的属性的名称;
			 ref:service类中的对象属性的Bean的id;(一般属性使用value,对象属性使用ref引用对象的Bean id) -->
		<property name="userDao" ref="userDao"></property>
	</bean>
	
	<!-- 注入复杂类型属性 -->
	<bean id="person" class="cn.itcast.d_complextype.Person">
		<property name="array">
			<list>
				<value>array1</value>
				<value>array2</value>
			</list>
		</property>
		<property name="list">
			<list>
				<value>list1</value>
				<value>list2</value>
			</list>
		</property>
		<property name="map">
			<map>
				<entry key="a" value="mapa"></entry>
				<entry key="b" value="mapb"></entry>
			</map>
		</property>
		<property name="properties">
			<props>
				<prop key="username">zhang</prop>
				<prop key="password">123456</prop>
			</props>
		</property>
	</bean>
	
	<!-- 开启注解扫描:批量扫描指定包下的带Bean注解的类、方法、属性
		  若要指定多个包,用逗号隔开,或者只写多个包名的前面相同的部分:cn.itcast -->
	<context:component-scan base-package="cn.itcast.e_annotation"></context:component-scan>
	<!-- 值扫描属性上面的注解 -->
	<!-- <context:annotation-config></context:annotation-config> -->
	
	<!-- 配置文件和注解混合使用:使用配置文件完成对象的创建; -->
	<bean id="bookDao" class="cn.itcast.f_xmlannotation.BookDao"></bean>
	<bean id="bookService" class="cn.itcast.f_xmlannotation.BookService"></bean>
	
	<!-- 基于aspectj的AOP操作 - xml配置方式 -->
	<!-- 配置对象 -->
	<bean id="baseBook" class="cn.itcast.g_aop.BaseBook"></bean>
	<bean id="extendBook" class="cn.itcast.g_aop.ExtendBook"></bean>
	<!-- 配置aop操作 -->
	<aop:config>
		<!-- 配置切入点:指定需要被增强功能的类和方法 -->
		<aop:pointcut expression="execution(* cn.itcast.g_aop.BaseBook.*(..))" id="pointcut1"/>
		<!-- 配置切面:指定把哪个增强用到哪个切入点上面
			 ref:引用增强的对象的Bean Id -->
		<aop:aspect ref="extendBook">
			<!-- 配置增强类型
				 method:增强类里面使用哪个方法作为前置、后置、环绕增强;
				 pointcut1:把增强用到哪个切入点上; -->
			<aop:before method="before" pointcut-ref="pointcut1"/>
			<aop:after-returning method="after" pointcut-ref="pointcut1"/>
			<aop:around method="around" pointcut-ref="pointcut1"/>
		</aop:aspect>
	</aop:config>
	
	<!-- 基于aspectj的aop操作 - 基于注解的方式 -->
	<!-- 开启aop操作 -->
	<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
	<!-- 配置对象 -->
	<bean id="baseCar" class="cn.itcast.h_aopannotation.BaseCar"></bean>
	<bean id="extendCar" class="cn.itcast.h_aopannotation.ExtendCar"></bean>
	
	<!-- (1)配置c3p0数据库连接池 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<!-- 注入属性值 -->
		<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
		<property name="jdbcUrl" value="jdbc:mysql:///spring"></property>
		<property name="user" value="root"></property>
		<property name="password" value="123456"></property>
	</bean>
	
	<!-- (2)创建JdbcTemplate对象,在JdbcTemplate对象中注入DataSource对象;  -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!-- (3)创建dao对象,在dao对象中注入jdbcTemplate对象; -->
	<bean id="personDao" class="cn.itcast.j_c3p0.PersonDao">
		<!-- 注入jdbcTemplate对象 -->
		<property name="jdbcTemplate" ref="jdbcTemplate"></property>
	</bean>
	<!-- (4)创建service对象,在service中注入dao对象; -->
	<bean id="personService" class="cn.itcast.j_c3p0.PersonService">
		<!-- 注入personDao对象 -->
		<property name="personDao" ref="personDao"></property>
	</bean>

</beans>   

~ applicationContextTx.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans ...........
	<!-- (1)配置c3p0数据库连接池 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<!-- 注入属性值 -->
		<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
		<property name="jdbcUrl" value="jdbc:mysql:///spring"></property>
		<property name="user" value="root"></property>
		<property name="password" value="123456"></property>
	</bean>
	<!-- (2)创建JdbcTemplate对象,在JdbcTemplate对象中注入DataSource对象;  -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!-- (3)创建dao对象,在dao对象中注入jdbcTemplate对象; -->
	<bean id="ordersDao" class="cn.itcast.k_tx.OrdersDao">
		<!-- 注入jdbcTemplate对象 -->
		<property name="jdbcTemplate" ref="jdbcTemplate"></property>
	</bean>
	<!-- (4)创建service对象,在service中注入dao对象; -->
	<bean id="ordersService" class="cn.itcast.k_tx.OrdersService">
		<!-- 注入personDao对象 -->
		<property name="ordersDao" ref="ordersDao"></property>
	</bean>
	
	<!-- (1)配置事务管理器,在事务管理器中注入dataSource: -->
	<!-- <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean> -->
	<!-- (2)配置事务增强,引用事务管理器:做事务操作 -->
	<!-- <tx:advice id="txAdvice" transaction-manager="transactionManager">
		account*: 设置进行事务操作的方法匹配规则;方法名前面是account的方法进行事务操作
		<tx:attributes>  <!-- 事务属性定义 -->
			<tx:method name="account*" propagation="REQUIRED"/>
		</tx:attributes>
	</tx:advice> -->
	<!-- (3)配置切面:配置切入点、切面;   使用切点表达式语言定义目标方法 -->
 	<!-- <aop:config>
 	    <!-- 通过aop定义事务增强切面 -->
 		<aop:pointcut expression="execution(* cn.itcast.k_tx.OrdersService.*(..))" id="pointcut1"/>
 		<!-- 引用事务增强 -->
 		<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut1"/>
 	</aop:config> -->
 	
 	<!-- (1)配置事务管理器: -->
 	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!-- (2)配置事务注解:对使用注解配置声明式事务的Bean进行加工处理,以织入事务管理切面; -->
 	<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>   

~ cn.itcast.a_bean

public class User1 {
	public void add(){ System.out.println("add......");	}
	public static void main(String[] args) {
		User1 user = new User1();   // 原始方法
		user.add();
	}
}
public class User2 {
	public void add(){ System.out.println("User2......"); }
}
public class User2Factory {
	public static User2 getUser2(){ return new User2();	}
}
public class User3 {
	public void add(){ System.out.println("User3......"); }
}
public class User3Factory {
	public User3 getUser3(){ return new User3(); }
}
public class UserTest {
	@Test
	public void testUser1() {
		// 加载spring配置文件,创建applicationContext对象
		ApplicationContext context = 
				new ClassPathXmlApplicationContext("applicationContext.xml");
		// 通过配置文件中配置的bean的id值,获取类的对象实例
		User1 user1 = (User1) context.getBean("user1");
		System.out.println(user1);
		user1.add();
	}
	@Test
	public void testUser2() {
		// 加载spring配置文件,创建applicationContext对象
		ApplicationContext context = 
				new ClassPathXmlApplicationContext("applicationContext.xml");
		// 通过配置文件中配置的bean的id值,获取类的对象实例
		User2 user2 = (User2) context.getBean("user2");
		System.out.println(user2);
		user2.add();
	}
	@Test
	public void testUser3() {
		// 加载spring配置文件,创建applicationContext对象
		ApplicationContext context = 
				new ClassPathXmlApplicationContext("applicationContext.xml");
		// 通过配置文件中配置的bean的id值,获取类的对象实例
		User3 user3 = (User3) context.getBean("user3");
		System.out.println(user3);
		user3.add();
	}
}

~ cn.itcast.b_peoperty

public class PropertyDemo1 {
	private String username;
	public void setUsername(String username) {	this.username = username;}
	public void test(){	System.out.println("PropertyDemo1..." + username);}
}
public class PropertyDemo2 {
	private String username;
	public PropertyDemo2(String username) {this.username = username; }
	public void test(){	System.out.println("PropertyDemo2..." + username); }
}
public class PropertyTest {
	@Test
	public void testPropertyDemo1() throws Exception {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		PropertyDemo1 propertyDemo1 = (PropertyDemo1) context.getBean("propertyDemo1p");
		propertyDemo1.test();
	}
	@Test
	public void testPropertyDemo2() {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		PropertyDemo2 propertyDemo2 = (PropertyDemo2) context.getBean("propertyDemo2");
		propertyDemo2.test();
	}
}

~ cn.itcast.c_objectproperty

public class UserDao {
	public void add(){System.out.println("UserDao......");	}
}
public class UserService {	
	private UserDao userDao;    // 定义dao类型的属性
	// 生成dao类型的属性的set方法
	public void setUserDao(UserDao userDao) {this.userDao = userDao;}
	public void add(){
		System.out.println("UseService......");
		userDao.add();  // 在service里面得到dao对象,通过dao对象调用dao对象的方法
	}
}

~ cn.itcast.d_complextype

public class Person {
	private String[] array;
	private List<String> list;
	private Map<String, String> map;
	private Properties properties;
	// set方法
	public void test(){
		System.out.println("array:" + array);
		System.out.println("list:" + list);
		System.out.println("map:" + map);
		System.out.println("properties:" + properties);
	}
}
public class PersonTest {
	@Test
	public void testTest() {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		Person person = (Person) context.getBean("person");
		person.test();
	}
}

~ cn.itcast.e_annotation

@Component(value="items") // <bean id="user" class="" />
@Scope(value="prototype") // 指定创建的对象是单例还是多例(默认单例)
public class Items {
	public void test(){ System.out.println("items.......");	}
}
@Component("itemsDao") // value= 可省略
public class ItemsDao {
	public void test(){	System.out.println("ItemsDao......");}
}
@Service(value="itemsService")
public class ItemsService {
	// 在UserDao对象上使用注解完成属性值(对象)的注入
	//@Autowired                // 根据类名找到类名对应的对象,跟注解属性中定义的名称无关
	@Resource(name="itemsDao") // name属性的值是注解创建对象的value值; 
	private ItemsDao itemsDao;  // 使用注解方式注入对象类型的属性值时不需要使set方法
	public void test(){
		System.out.println("ItemsService......");
		itemsDao.test();
	}
}

~ cn.itcast.f_xmlannotation

public class BookDao {
	public void test(){	System.out.println("BookDao......");	}
}
public class BookService {
	@Resource(name="bookDao")
	private BookDao bookDao;
	public void test(){
		System.out.println("BookService......");
		bookDao.test();
	}
}

~ cn.itcast.g_aop

public class BaseBook { // 需要被增强功能的类
	public void test(){ System.out.println("BaseBook......");	}
}
public class ExtendBook {  // 增强类
	public void before(){	System.out.println("前置增强......");	}
	public void after(){	System.out.println("后置增强......");	}
	public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
		System.out.println("环绕增强—方法之前......");
		proceedingJoinPoint.proceed();  // 执行被增强的方法
		System.out.println("环绕增强—方法之后......");
	}
}

~ cn.itcast.h_aopannotation

public class BaseCar {
	public void test() {	System.out.println("BaseCar......");	}
}
@Aspect  // 将增强类定义为切面:把增强用到切入点
public class ExtendCar {
	// 在方法上面使用注解完成增强配置:value值配置切入点
	@Before(value="execution(* cn.itcast.h_aopannotation.BaseCar.*(..))")
	public void before(){	System.out.println("前置增强");	}
}

~ cn.itcast.i_jdbc

public class UserInfo {
	private Integer id;
	private String username;
	private String password;
    // set/get方法
}
public class JdbcTemplateDemo {
	// 0、原始Jdbc代码实现对数据的操作
	@Test
	public void testJdbc(){
		Connection conn = null;
		PreparedStatement psmt = null;
		ResultSet rs = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");  // 加载数据库驱动                  // 创建数据库连接
			conn = DriverManager.getConnection("jdbc:mysql:///spring","root","123456"); 
			String sql = "select * from user where username=?";  // 编写sql语句
			psmt = conn.prepareStatement(sql);                   // 预编译sql
			psmt.setString(1, "非墨");                            // 设置参数值
			rs = psmt.executeQuery();                            // 执行sql
			while(rs.next()){                                    // 遍历结果集
				String username = rs.getString("username");      // 得到返回结果值
				String password = rs.getString("password");
				UserInfo userInfo = new UserInfo();              // 把数据放到UserInfo对象里
				userInfo.setUsername(username);
				userInfo.setPassword(password);
				System.out.println(userInfo);
			}
		} catch (Exception e) {e.printStackTrace();
		} finally{
			try {
				rs.close();
				psmt.close();
				conn.close();
			} catch (SQLException e) { e.printStackTrace(); }
		}
	}
	// 1、添加操作
	@Test
	public void addUserInfo(){
		// 1、创建对象,设置数据库信息;
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql:///spring");
		dataSource.setUsername("root");
		dataSource.setPassword("123456");
		// 2、创建JdbcTemplate对象,设置数据源;
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		// 3、调用JdbcTemplate对象里面的update方法实现添加操作;
		// 创建sql语句
		String sql = "insert into user(username,password) values(?,?)";
		int rows = jdbcTemplate.update(sql, "叶琛","111111");
		System.out.println(rows);
	}
	// 2、删除操作
	@Test
	public void deleteUserInfo(){
		// 1、创建对象,设置数据库信息;
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql:///spring");
		dataSource.setUsername("root");
		dataSource.setPassword("123456");
		// 2、创建JdbcTemplate对象,设置数据源;
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		// 3、调用JdbcTemplate对象里面的update方法实现删除操作;
		String sql = "delete from user where username=?";
		int rows = jdbcTemplate.update(sql, "温暖");
		System.out.println(rows);
	}
	// 3、更新操作
	@Test
	public void updateUserInfo(){
		// 1、创建对象,设置数据库信息;
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql:///spring");
		dataSource.setUsername("root");
		dataSource.setPassword("123456");
		// 2、创建JdbcTemplate对象,设置数据源;
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		// 3、调用JdbcTemplate对象里面的update方法实现更新操作;
		String sql = "update user set password=? where username=?";
		int rows = jdbcTemplate.update(sql, "123123","墨小白");
		System.out.println(rows);
	}
	// 4、查询操作
	// JdbcTemplate实现查询操作,有RowMapper接口,但针对这个接口没有提供实现类,得到不同类型的数据需要自己进行数据的封装;
	// (1)查询返回某一个值:查询表中有多少条记录
	@Test
	public void queryCount(){
		// 1、创建对象,设置数据库信息;
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql:///spring");
		dataSource.setUsername("root");
		dataSource.setPassword("123456");
		// 2、创建JdbcTemplate对象,设置数据源;
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		// 3、调用方法得到记录数
		String sql = "select count(*) from user";
		// 调用JdbcTemplate的query方法
		// 第一个参数:sql语句; 第二个参数:返回值的类型的class;
		int count = jdbcTemplate.queryForObject(sql, Integer.class);
		System.out.println(count);
	}
	// (2)查询返回对象
	@Test
	public void testObject(){
		// 1、创建对象,设置数据库信息;
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql:///spring");
		dataSource.setUsername("root");
		dataSource.setPassword("123456");
		// 2、创建JdbcTemplate对象,设置数据源;
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		// 3、根据username查询用户信息
		String sql = "select * from user where username=?";
		// 调用JdbcTemplate的query方法
		// 第一个参数:sql语句; 第二个参数:RowMapper接口,需要自己实现; 第三个参数:可变参数;
		UserInfo userInfo = jdbcTemplate.queryForObject(sql, new MyRowMapper(), "墨小白");
		System.out.println(userInfo);
	}
	// (3)查询返回list集合
	@Test
	public void testList(){
		// 1、创建对象,设置数据库信息;
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql:///spring");
		dataSource.setUsername("root");
		dataSource.setPassword("123456");
		// 2、创建JdbcTemplate对象,设置数据源;
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		// 3、查询所有用户信息
		String sql = "select * from user";
		// 调用JdbcTemplate的query方法
		// 第一个参数:sql语句; 第二个参数:RowMapper接口,自己实现的; 	
		List<UserInfo> list = jdbcTemplate.query(sql, new MyRowMapper());
		System.out.println(list);
	}
}
class MyRowMapper implements RowMapper<UserInfo> {
	@Override
	public UserInfo mapRow(ResultSet rs, int num) throws SQLException {
		// 1、从结果集里面得到数据
		String username = rs.getString("username");
		String password = rs.getString("password");
		// 2、把得到的数据封装到对象里面
		UserInfo userInfo = new UserInfo();
		userInfo.setUsername(username);
		userInfo.setPassword(password);
		return userInfo;
	}
}

~ cn.itcast.j_c3p0

public class PersonDao {
	// 得到JdbcTemplate对象
	private JdbcTemplate jdbcTemplate;
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	// 添加操作
	public void add(){
		String sql = "insert into user(username,password) values(?,?)";
		// 直接调用jdbcTemplate模板对象,对象的创建在spring配置文件中完成并注入;
		jdbcTemplate.update(sql,"叶琰","112233");
	}
}
public class PersonService {
	// 创建personDao属性
	private PersonDao personDao;
	public void setPersonDao(PersonDao personDao) {
		this.personDao = personDao;
	}
	public void add(){
		personDao.add(); // 直接调用personDao的方法;
	}
}

~ cn.itcast.k_tx

public class OrdersDao {
	// 注入JdbcTemplate模板对象
	private JdbcTemplate jdbcTemplate;
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	// Dao层做对数据库的操作的方法,不写业务逻辑;
	// 墨遥少钱的方法
	public void lessMoney(){
		String sql = "update account set salary=salary-? where username=?";
		jdbcTemplate.update(sql, 1000,"墨遥");
	}
	// 墨晨多钱的方法
	public void moreMoney(){
		String sql = "update account set salary=salary+? where username=?";
		jdbcTemplate.update(sql, 1000,"墨晨");
	}
} 
@Transactional
public class OrdersService {
	private OrdersDao ordersDao;
	public void setOrdersDao(OrdersDao ordersDao) {	this.ordersDao = ordersDao;	}
	// 业务逻辑层调用Dao层的方法,写转账业务
	public void accountMoney(){
		ordersDao.lessMoney();  // 墨遥少1000
		int i = 10/0;           // 出现异常
		ordersDao.moreMoney();  // 墨晨多1000
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值