Spring笔记

Spring笔记

Spring体系结构

Spring体系结构

核心容器

  • Spring-core模块:提供了框架的基本组成部分,包括控制反转(Inversion of Control,IoC)和依赖注入(Dependency Injection,DI)功能。
  • Spring-beans模块:提供了BeanFactory,是工厂模式的一个经典实现,Spring将管理对象称为Bean。
  • Spring-context模块:建立在Core和Beans模块基础上,提供一个框架式的对象访问方式,是访问定义和配置的任何对象的媒介。ApplicationContext接口是Context模块的焦点。
  • Spring-context-support模块:支持整合第三方库到Spring应用程序上下文,特别是用于高速缓存(EhCache,JCache)和任务调度(CommonJ,Quartz)的支持。
  • Spring-expression模块:提供了强大的表达式语言去支持运行时查询和操作对象图。

IOC(控制反转)

依赖注入特点

  • 调用者代码采用接口的方式定义,面向接口编程,而不必要知道Spring 具体的类实现。而Spring 可以通过修改配置文件来切换底层的实现类。

ApplicationContext

  • ApplicationContext是BeanFactory的子接口,大部分JavaEE应用,使用它作为Spring容器更方便。
  • 常用的ApplicationContext的实现类为:
    FileSystemXmlApplicationContext:以基于文件系统的XML配置文件创建ApplicationContext 实例。从项目路径下开始找
    ClassPathXmlApplicationContext :以类加载路径下的XML配置文件创建ApplicationContext 实例。从src目录下开始找

通过Web服务器实例化ApplicationContext容器

<context-param>
  	<!-- 加载src目录下的applicationContext.xml文件 -->
  	<param-name>contextConfigLocation</param-name>
  	<param-value>
  		classpath:applicationContext.xml
  	</param-value>
  </context-param>
  <!-- 指定以ContextLoaderListener方式启动Spring容器 -->
  <listener>
  	<listener-class>
  		org.springframework.web.context.ContextLoaderListener
  	</listener-class>
  </listener>

基于XML

  • 获取Spring容器对象:ApplicationContext ac = new ClassPathApplicationContext("ApplicationContext.xml")
  • 通过Spring容器获取实例对象:
    IAccountService as = (AccountServiceImpl)ac.getBean("accountService")
    IAccountService as =ac.getBean("accountService",AccountServiceImpl.class)

XML配置

  • 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">
</beans>
  • 配置bean
<!-- bean 标签:用于配置让 spring 创建对象,并且存入 ioc 容器之中
	id 属性:对象的唯一标识。
	class 属性:指定要创建对象的全限定类名 --> 
<!-- 配置 service -->    
<bean id="accountService" class="com.X1a0Wu.itheima.service.impl.AccountServiceImpl"> </bean> 
<!-- 配置 dao --> 
<bean id="accountDao" class="com.X1a0Wu.dao.impl.AccountDaoImpl"></bean> 

bean细节

  • bean标签
作用:
	用于配置对象让 spring 来创建的。  
	默认情况下它调用的是类中的无参构造函数。如果没有无参构造函数则不能创建成功。 
	属性:  
		id:给对象在容器中提供一个唯一标识。用于获取对象。  
		class:指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数。  
		scope:指定对象的作用范围。    
			* singleton :默认值,单例的.    
			* prototype :多例的.    
			* request :WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 request 域中.
			* session :WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 session 域中. 
			* global session :WEB 项目中,应用在 Portlet 环境.如果没有 Portlet 环境那么 globalSession 相当于 session. 
		init-method:指定类中的初始化方法名称。  
		destroy-method:指定类中销毁方法名称。
  • bean 的作用范围和生命周期
单例对象:scope="singleton"   
	一个应用只有一个对象的实例。它的作用范围就是整个引用。  
	生命周期:    
		对象出生:当应用加载,创建容器时,对象就被创建了。    
		对象活着:只要容器在,对象一直活着。    
		对象死亡:当应用卸载,销毁容器时,对象就被销毁了。  
多例对象:scope="prototype"   
	每次访问对象时,都会重新创建对象实例。   
	生命周期:    
		对象出生:当使用对象时,创建新的对象实例。    
		对象活着:只要对象在使用中,就一直活着。    
		对象死亡:当对象长时间不用时,被 java 的垃圾回收器回收了
  • 实例化 Bean 的三种方式
  1. 第一种方式:使用默认无参构造函数
	<!--在默认情况下:   它会根据默认无参构造函数来创建类对象。如果 bean 中没有默认无参构造函数,将会创建失败。-->
<bean id="accountService" class="com.X1a0Wu.service.impl.AccountServiceImpl"/>

2.第二种方式:spring管理静态工厂-使用静态工厂的方法创建对象

<!--
 /**
 * 模拟一个静态工厂,创建业务层实现类
*/
public class StaticFactory {
	public static IAccountService createAccountService(){
		return new AccountServiceImpl();  } } 
-->
<!-- 此种方式是:
	使用 StaticFactory 类中的静态方法 createAccountService 创建对象,并存入 spring 容器
	id 属性:指定 bean 的 id,用于从容器中获取
	class 属性:指定静态工厂的全限定类名
	factory-method 属性:指定生产对象的静态方法  -->
<bean id="accountService"  class="com.X1aoWu.factory.StaticFactory" factory-method="createAccountService"></bean>
  1. spring管理实例工厂-使用实例工厂的方法创建对象
/**
 * 模拟一个实例工厂,创建业务层实现类
 * 此工厂创建对象,必须现有工厂实例对象,再调用方法  */
public class InstanceFactory {
	public IAccountService createAccountService(){
		return new AccountServiceImpl();  } }
 <!-- 此种方式是:
	先把工厂的创建交给 spring 来管理。
	然后在使用工厂的 bean 来调用里面的方法
	factory-bean属性:用于指定实例工厂 bean 的 id.
	factory-method 属性:用于指定实例工厂中创建对象的方法。  --> 
 <bean id="instancFactory" class="com.X1aoWu.factory.InstanceFactory"></bean>  
 <bean id="accountService"  factory-bean="instancFactory"  factory-method="createAccountService"></bean>

依赖注入

  1. 构造函数注入
//顾名思义,就是使用类中的构造函数,给成员变量赋值。注意,赋值的操作不是我们自己做的,而是通过配置的方式,让 pring框架来为我们注入。具体代码如下
public class AccountServiceImpl implements IAccountService {
	private String name;
	private Integer age;
	private Date birthday;
	public AccountServiceImpl(String name, Integer age, Date birthday) {
		this.name = name;
		this.age = age;
		this.birthday = birthday;
	}
	 @Override
	 public void saveAccount() {
		 System.out.println(name+","+age+","+birthday);
	 }
}
<-使用构造函数的方式,给 service中的属性传值
	要求:
		类中需要提供一个对应参数列表的构造函数
	涉及的标签:
	constructor-arg:
		属性:
			index:指定参数在构造函数参数列表的索引位置
			type:指定参数在构造函数中的数据类型
			name:指定参数在构造函数中的名称     用这个找给谁赋值
    =======上面三个都是找给谁赋值,下面两个指的是赋什么值的==============
			value:它能赋的值是基本数据类型和 String 类型
			ref:它能赋的值是其他 bean 类型,也就是说,必须得是在配置文件中配置过的 bean
--> 
<bean id="accountService" class="com.X1a0Wu.service.impl.AccountServiceImpl">
	<constructor-arg name="name" value=" 张三 "></constructor-arg>
	<constructor-arg name="age" value="18"></constructor-arg> 
	<constructor-arg name="birthday" ref="now"></constructor-arg>
</bean>
<bean id="now" class="java.util.Date"></bean>

优点:

  • 可以在构造器中决定依赖关系的注入顺序,优先依赖的优先注入。
  • 对于依赖关系无须变化的Bean,不提供set方法,可以避免后续的代码对原有bean 的破坏。
  • 只有组件的创建者可以实现依赖关系,组件内部的依赖关系完全透明,更符合高内聚的原则
  1. set方法注入
//顾名思义,就是在类中提供需要注入成员的 set 方法。具体代码如下:
public class AccountServiceImpl implements IAccountService {    
	private String name;  
	private Integer age;  
	private Date birthday;    
	public void setName(String name) {   
		this.name = name;  
	}  
	public void setAge(Integer age) {   
		this.age = age;  
	} 
	public void setBirthday(Date birthday) {   
		this.birthday = birthday;  
	} 
 
 	@Override
 	public void saveAccount() {   
		 System.out.println(name+","+age+","+birthday);   
	} 
}
<!-- 通过配置文件给 bean 中的属性传值:使用 set 方法的方式  
	涉及的标签:   
		property 
			属性:    
				name:找的是类中 set 方法后面的部分 
				ref:给属性赋值是其他 bean 类型的
				value:给属性赋值是基本数据类型和 string 类型的
	实际开发中,此种方式用的较多。
--> 
<bean id="accountService" class="com.X1a0Wu.service.impl.AccountServiceImpl">   		<property name="name" value="test"></property> 
	<property name="age" value="21"></property> 
	<property name="birthday" ref="now"></property> 
</bean>
 <bean id="now" class="java.util.Date"></bean> 
  • 优点
  • 与传统开发更接近,依赖关系更直观。
  • 对于复杂的依赖关系,构造注入会导致构造器过于臃肿,且需要同时实例化其依赖的全部实例。
  • 设值注入可以延迟注入的时间,并按需注入。不必要实例化所有的依赖Bean。
  • 在有些参数可选的时候,设值注入显得更灵活。
    3.注入集合数据
//顾名思义,就是给类中的集合成员传值,它用的也是set方法注入的方式,只不过变量的数据类型都是集合。 我们这里介绍注入数组,List,Set,Map,Properties。具体代码如下:
public class AccountServiceImpl implements IAccountService {
	private String[] myStrs;
	private List<String> myList;
	private Set<String> mySet;
	private Map<String,String> myMap;
	private Properties myProps;
	public void setMyStrs(String[] myStrs) {
		this.myStrs = myStrs;
	}
	public void setMyList(List<String> myList) {
		this.myList = myList;
	}
	public void setMySet(Set<String> mySet) {
		this.mySet = mySet;
	}
	public void setMyMap(Map<String, String> myMap) {
		this.myMap = myMap;
	}
	public void setMyProps(Properties myProps) {
		this.myProps = myProps;
	} 
	@Override  public void saveAccount() {
		System.out.println(Arrays.toString(myStrs));
		System.out.println(myList);
		System.out.println(mySet);
		System.out.println(myMap); 
		System.out.println(myProps);
	} 
}
<!--
	注入集合数据 
		List 结构的:   array,list,set 
		Map 结构的   map,entry,props,prop 
--> 
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"> 
 	<!-- 在注入集合数据时,只要结构相同,标签可以互换 -->
 	<!-- 给数组注入数据 --> 
 	<property name="myStrs"> 
		<set>
			<value>AAA</value>
			<value>BBB</value>
			<value>CCC</value>
		</set> 
	</property> 
 	<!-- 注入 list 集合数据 -->
	 <property name="myList">
	 	<array>
		 	<value>AAA</value>
			<value>BBB</value>
			<value>CCC</value>
		</array>
	</property> 
 	<!-- 注入 set 集合数据 --> 
	 <property name="mySet"> 
 		<list>
		 	<value>AAA</value>
			<value>BBB</value>
			<value>CCC</value>
		</list>
	</property> 
	<!-- 注入 Map 数据 -->
	<property name="myMap">
		<props> 
			<prop key="testA">aaa</prop>
			<prop key="testB">bbb</prop>
		</props> 
 	</property> 
	<!-- 注入 properties 数据 --> 
	<property name="myProps"> 
		<map>
			<entry key="testA" value="aaa"></entry> 
			<entry key="testB">
				<value>bbb</value> 
			</entry>
		</map>
	</property> 
</bean> 

延迟初始化Bean

  • BeanFactory要等到程序需要Bean实例时才创建Bean
  • ApplicationContext在创建ApplicationContext实例时,会预初始化容器中所有的singleton Bean
  • 如果不希望一个singleton Bean在启动时被初始化,而在第一次使用时才进行初始化,使用lazy-init属性
<bean id=“steelAxe” class=“org.impl.StellAxe” lazy-init=“true”/>

强制初始化Bean

  • BeanFactory初始化Bean时,是先初始化主调Bean ,后初始化依赖Bean
  • ApplicationContext依照bean在配置文件中的声明顺序对各个Bean进行初始化,其延迟初始化顺序的情况同BeanFactory
  • 强制使依赖Bean提前初始化,使用depends-on属性
<bean id=“beanOne” class=“ExampleBean” depends-on=“manager”>
      <property name=“manager” ref=“manager” />
</bean>
<bean id=“manager” class=“ManagerBean” />

基于注解

XML内容

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" 
	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
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd"> 

 	<!-- 告知 spring 创建容器时要扫描的包 -->  		<context:component-scan base-package="com.itheima"></context:component-scan>
</beans>

用于创建对象的注解

相当于:<bean id="" class="">

  • @Component
作用:
	把资源让 spring 来管理。相当于在 xml 中配置一个 bean。
属性:
	value:指定 bean 的 id。如果不指定 value 属性,默认 bean的 id 是当前类的类名。首字母小写。 
  • @Controller @Service @Repository
他们三个注解都是针对一个的衍生注解,他们的作用及属性都是一模一样的。
他们只不过是提供了更加明确的语义化。
	@Controller:一般用于表现层的注解。
	@Service:一般用于业务层的注解。
	@Repository:一般用于持久层的注解。
细节:如果注解中有且只有一个属性要赋值时,且名称是 value,value在赋值是可以不写。 

用于注入数据的注解

相当于<property name="" ref=""> <property name="" value="">

  • @Autowired
作用:
	自动按照类型注入。当使用注解注入属性时,set方法可以省略。它只能注入其他 bean 类型。当有多个 类型匹配时,使用要注入的对象变量名称作为 bean 的 id,在 spring 容器查找,找到了也可以注入成功。找不到 就报错。  
  • @Qualifier
作用:
	在自动按照类型注入的基础之上,再按照 Bean 的 id 注入。它在给字段注入时不能独立使用,必须和 @Autowire 一起使用;但是给方法参数注入时,可以独立使用。
属性:
	value:指定 bean 的 id。 
  • @Resource
作用:
	直接按照 Bean 的 id 注入。它也只能注入其他 bean 类型。
属性:
	name:指定 bean 的 id。 
  • @Value
作用:
	注入基本数据类型和 String 类型数据的
属性:
	value:用于指定值 

用于改变作用范围的注解

相当于scope=

  • @Scope
作用:
	指定 bean 的作用范围。
属性:
	value:指定范围的值。
		取值:singleton  prototype request session

Spring注解和XML选择

  • 注解的优势: 配置简单,维护方便(我们找到类,就相当于找到了对应的配置)。
  • XML 的优势: 修改时,不用改源码。不涉及重新编译和部署。
  • 二者的比较:
比较基于XML配置基于注解配置
Bean定义<bean id="…“class=”…"/>@Component 衍生类@Repository @Service @Controller
Bean名称通过id或name指定@Component(“person”)
Bean注入<property>@Auto按类型注入或@Qualifie按名称注入
适合场景Bean来自第三方Bean的实现类由用户自己开发

新注解

  • @Configuration
作用:
	用于指定当前类是一个 spring 配置类,当创建容器时会从该类上加载注解。获取容器时需要使用 AnnotationApplicationContext(有@Configuration 注解的类.class)。
属性:
	value:用于指定配置类的字节码
细节:
	当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写
  • @ComponentScan
作用:
	用于指定 spring 在初始化容器时要扫描的包。作用和在 spring 的 xml 配置文件中的: <context:component-scan base-package="com.itheima"/>是一样的。
属性:
	basePackages:用于指定要扫描的包。和该注解中的 value 属性作用一样。 
  • @Bean
作用:
	该注解只能写在方法上,表明使用此方法创建一个对象,并且放入 spring 容器。
属性:
	name:给当前@Bean 注解方法创建的对象指定一个名称(即 bean 的 id)
细节:
	当我们使用注解配置方法时,如果方法有参数,Spring框架会去容器中查找有没有可用的Bean对象,查找的方式和Autowired注解的作用是一样的
  • @Import
作用:
	用于导入其他配置类,在引入其他配置类时,可以不用再写@Configuration 注解。当然,写上也没问题。
属性:
	value[]:用于指定其他配置类的字节码。
示例代码:
	@Configuration
	@ComponentScan(basePackages = "com.itheima.spring"
	@Import({ JdbcConfig.class}
  • PropertySource
作用:
	用于加载.properties 文件中的配置。例如我们配置数据源时,可以把连接数据库的信息写到 properties 配置文件中,就可以使用此注解指定 properties 配置文件的位置。
属性:
	value[]:用于指定 properties 文件位置。如果是在类路径下,需要写上 classpath: 

AOP

AOP概念

AOP术语

  • 切面(Aspect)是指封装横切到系统功能(如事务处理)的类。
  • 连接点(Joinpoint)是指程序运行中的一些时间点,如方法的调用或异常的抛出。
  • 切入点(Pointcut)是指那些需要处理的连接点。在Spring AOP 中,所有的方法执行都是连接点,而切入点是一个描述信息,它修饰的是连接点,通过切入点确定哪些连接点需要被处理。
  • 通知(增强处理Advice)
    由切面添加到特定的连接点(满足切入点规则)的一段代码,即在定义好的切入点处所要执行的程序代码。可以将其理解为切面开启后,切面的方法。因此,通知是切面的具体实现。
  • 组入(Weaving)是将切面代码插入到目标对象上,从而生成代理对象的过程。根据不同的实现技术

基于XML配置开发AspectJ

<aop:config>
	 <!-- 配置切面 -->
	 <aop:aspect ref="myAspectJ">
	 	<!-- 配置切入点,通知在哪些方法进行增强 
	 		在gzc.dao包下的所有类方法以及其子包的所有类的方法
	 	-->
	 	<aop:pointcut expression="execution(* gzc.dao..*.*(..))" id="myPointcut"/>
	 	<!-- 关联前置通知 -->
	 	<aop:before method="before" pointcut-ref="myPointcut"/>
	 	<!-- 关联后置返回通知 目标方法成功执行后才执行-->
	 	<aop:after-returning method="afterReturning" pointcut-ref="myPointcut" />
	 	<!-- 关联环绕通知 -->
	 	<aop:around method="around" pointcut-ref="myPointcut"/>
	 	<!-- 关联异常通知 只有目标方法出现异常时才执行 , throwing设置通知的第二个参数名称-->
	 	<aop:after-throwing method="except" pointcut-ref="myPointcut" throwing="e"/>
	 	<!-- 关联最终通知 不管目标方法是否成功都要执行-->
	 	<aop:after method="after" pointcut-ref="myPointcut" />
	</aop:aspect>
</aop:config>

在这里插入图片描述

package gzc.aspectj.xml;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
/**
 * 切面类 ,在此类中编写各种类型通知
 */
public class MyAspectJ {
	// 前置通知,使用JoinPoint接口作为参数获得目标对象
	public void before(JoinPoint jp) {
		System.out.print("前置通知:模拟权限控制");
		System.out.println(",目标对象:" + jp.getTarget() + ",被增强的方法:" + jp.getSignature().getName());
	}
	// 后置返回通知 , 目标方法成功执行后才执行
	public void afterReturning(JoinPoint jp) {
		System.out.print("后置返回通知:模拟缓存清理");
		System.out.println(",目标对象:" + jp.getTarget() + ",被增强的方法:" + jp.getSignature().getName());
	}
	/*
	 * 环绕通知 ProceedingJoinPoint 是JoinPoint的子接口,代表可以执行的目标方法 返回值类型必须是Object
	 * 必须一个参数是ProceedingJoinPoint类型 必须throws Throwable
	 */
	public Object around(ProceedingJoinPoint pjp) throws Throwable {
		Object obj = null;
		System.out.println("环绕开始,执行目标方法前,模拟开启事务");
		// 执行目标方法
		obj = pjp.proceed();
		// 结束
		System.out.println("环绕结束,执行目标方法后前,模拟关闭事务");
		return obj;
	}
	// 异常通知
	public void except(JoinPoint jp, Throwable e) {
		System.out.println("异常通知:执行程序异常" + e.getMessage());
	}
	// 后置(最终)通知,不管目标方法是否成功都要执行
	public void after(JoinPoint jp) {
		System.out.println("后置(最终)通知,目标对象:" + jp.getTarget() + ",被增强的方法:" + jp.getSignature().getName());
	}
}

基于注解开发AspectJ

package gzc.aspectj.annotation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/*	@Aspect : 对应<aop:aspect ref="aspectJByAnnotation">
 *	@Component : <bean id="aspectJByAnnotation" class="gzc.aspectj.annotation.AspectJByAnnotation"/>
 */
@Aspect
@Component
public class AspectJByAnnotation {
	/*
	 * 定义切入点 如果不以这种方式定义切入点,则需要在每个通知的注解传入expression表达式作为参数
	 * 例如 @Before("execution(* gzc.dao..*.*(..))")
	 */
	@Pointcut("execution(* gzc.dao..*.*(..))")
	public void myPointcut() {
		// 相当于 <aop:pointcut expression="execution(* gzc.dao..*.*(..))"
		// id="myPointcut"/>
	}

	// 前置通知,使用JoinPoint接口作为参数获得目标对象
	@Before("myPointcut()")
	public void before(JoinPoint jp) {
		System.out.print("前置通知:模拟权限控制");
		System.out.println(",目标对象:" + jp.getTarget() + ",被增强的方法:" + jp.getSignature().getName());
	}
	
	@AfterReturning(value = "myPointcut",returning = "rst")
	// 后置返回通知 , 目标方法成功执行后才执行
	public void afterReturning(JoinPoint jp Integer  rst) {
		System.out.print("后置返回通知:模拟缓存清理");
		System.out.println(",目标对象:" + jp.getTarget() + ",被增强的方法:" + jp.getSignature().getName());
	}
	
	/*
	 * 环绕通知 ProceedingJoinPoint 是JoinPoint的子接口,代表可以执行的目标方法 返回值类型必须是Object
	 * 必须一个参数是ProceedingJoinPoint类型 必须throws Throwable
	 */
	@Around("myPointcut()")
	public Object around(ProceedingJoinPoint pjp) throws Throwable {
		Object obj = null;
		System.out.println("环绕开始,执行目标方法前,模拟开启事务");
		// 执行目标方法
		obj = pjp.proceed();
		// 结束
		System.out.println("环绕结束,执行目标方法后前,模拟关闭事务");
		return obj;
	}
	
	// 异常通知
	@AfterThrowing(value = "myPointcut()", throwing = "e")
	public void except(JoinPoint jp, Throwable e) {
		System.out.println("异常通知:执行程序异常" + e.getMessage());
	}
	
	// 后置(最终)通知,不管目标方法是否成功都要执行
	@After("myPointcut()")
	public void after(JoinPoint jp) {
		System.out.println("后置(最终)通知,目标对象:" + jp.getTarget() + ",被增强的方法:" + jp.getSignature().getName());
	}
}

数据库编程

<?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-4.3.xsd">
	<!-- 1.配置数据源 -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<!-- 1.1.数据库驱动 -->
		<property name="driverClassName"
			value="com.mysql.jdbc.Driver"></property>
		<!-- 1.2.连接数据库的url -->
		<property name="url"
			value="jdbc:mysql://localhost:3306/spring?characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=UTC&amp;rewriteBatchedStatements=true"></property>
		<!-- 1.3.连接数据库的用户名 -->
		<property name="username" value="root"></property>
		<!-- 1.4.连接数据库的密码 -->
		<property name="password" value="12345678"></property>
	</bean>

	<!-- 2配置JDBC模板 -->
	<bean id="jdbcTemplate"
		class="org.springframework.jdbc.core.JdbcTemplate">
		<!-- 默认必须使用数据源 -->
		<property name="dataSource" ref="dataSource"></property>
	</bean>
</beans>
package bean.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.List;
import bean.DBBean;
import bean.vo.GoodsVo;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;

@Repository("goodsDao")
public class GoodsDaoimpl implements IGoodsDao {

	@Resource(name = "jdbcTemplate")
	JdbcTemplate jdbcTemplate;
	//每页数量
	int numPerPage = 2;
	//按照页数查询,结果返回一个List
	public List<GoodsVo> getGoodsByPage(int pageNo){


		int beginIndex = (pageNo - 1)*numPerPage;
		
		String sql = "select * from goods limit " + beginIndex + "," + numPerPage;
		System.out.println(sql);

		RowMapper<GoodsVo> rowMapper = new BeanPropertyRowMapper<GoodsVo>(GoodsVo.class);
		return jdbcTemplate.query(sql, rowMapper, null);

	}
	
	//按照id查询,结果返回一个对象
	public GoodsVo getGoodsById(Integer goodsId){


		String sql = "select * from goods where goodsid = ?";

//		RowMapper<GoodsVo> rowMapper = new BeanPropertyRowMapper<GoodsVo>(GoodsVo.class);
		GoodsVo goodsVo = (GoodsVo) jdbcTemplate.queryForObject(sql,new Object[]{goodsId},new BeanPropertyRowMapper(GoodsVo.class)); 	
		System.out.println(goodsVo);
		return goodsVo;
	}
	
	//获得页数
	public int getPageCount(){

		String sql = "select count(*) from goods";
		int num = jdbcTemplate.queryForObject(sql,null,Integer.class);
		return (num-1)/numPerPage+1;
		
	}


}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值