j2ee开发之Spring2.5框架学习笔记

Spring 2.5框架学习笔记

1.是一个开源的控制反转IOC和面向切面AOP的容器框架

2.IOC控制反转

public class PersonServiceBean {

private PersonDao personDao = new PersonDao();

publiv void save(Person person){

personDao.save(person);

}

}

控制反转:应用本身不负责依赖对象personDao的创建以及维护,依赖对象的创建以及维护是由外部容器负责的,这样控制权就由应用转移到了外部的容器,控制权的转移就是反转。

3.依赖注入(Dependency injection)

依赖注入:在运行期间由外部容器动态地将依赖对象注入到组件中

改写的PersonServiceBean

public class PersonServiceBean {

private PersonDao persondao;

public PersonServiceBean(PersonDao persondao){

this.persondao=persondao;

}

public void save(Person person){

persondao.save(person);

}

}

利用了构造器,让容器把创建好的对象注入到PersonServiceBean,在构造器中将Dao层的对象注入到了业务层。

4.Spring不需要手工控制事务

5.重量级还是轻量级变量?

    使用的服务越多,容器为普通的java对象做得工作就越多,影响到应用的发布时间和运行性能。这时就是重量级的。对于spring容器,如果仅仅使用核心的服务,就是轻量级的。

6.环境搭建:

 

 

7.配置文件beans.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-2.5.xsd">

<bean id="personService" class="test.PersonServiceBean"></bean>

</beans>

8.spring的第一例子

//抽取的接口

package impls;

public interface PersonService {

public abstract void save();

}

//接口的实现方法

package service;

import impls.PersonService;

public class PersonServiceBean implements PersonService {

/* (non-Javadoc)

 * @see service.impl.PersonService#save()

 */

public void save(){

System.out.println("save function");

}

}

 

package test;

import impls.PersonService;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {

public static void setUpBeforeClass(){

}

public static void instanceSpring(){

//根据配置文件,创建一个spring容器的实例

ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

//从容器中,根据id,取得业务层对象

PersonService ps =(PersonService)ctx.getBean("personService");

//调用业务层对象的方法

ps.save();

}

}

 

9.spring实例化bean3种方法?最常用的是第一种,其他看到了读得懂就行。

<?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-2.5.xsd">

        <!-- 创建了bean,由容器维护,即将bean放在了容器中 -->

        <!-- 类的构造器实例化 -->

        <bean id="personService" class="service.PersonServiceBean"></bean>

        <!-- 静态工厂实例化 -->

        <bean id="personService2" class="service.PersonServiceBeanFactory" factory-method="createPersonService"></bean>

        <!-- 动态工厂方法实例化 -->

        <bean id="personServiceFactory" class="service.PersonServiceBeanFactory" >  </bean>

        <bean id="personService3" factory-bean="personServiceFactory" factory-method="createPersonService2"> </bean>

</beans>

 

package service;

public class PersonServiceBeanFactory {

//静态的工厂方法,createPersonService

//返回一个PersonServiceBean对象

public static PersonServiceBean createPersonService(){

return new PersonServiceBean();

}

//实例工厂方法

public PersonServiceBean createPersonService2(){

return new PersonServiceBean();

}

}

 

10.两次调用方法getBean(),是不是引用的是同一个对象?

是同一个对象,即使一个单实例对象。

默认:singleton作用域,单例模式,bean的实例化在创建容器时

prototype作用域下,每次调用会返回一个新的对象bean的实例化在容器调取bean

<bean id="personService" class="service.PersonServiceBean" scope="prototype"></bean>

scope="prototype"    scope="singleton"

setter方法注入:

11.类对象类型的注入

<!-- 类的构造器实例化 -->

<bean id="personDao" class="dao.PersonDaoBean"></bean>

<bean id="personService" class="service.PersonServiceBean" >

<property name="personDao" ref="personDao"></property>

</bean>

理解:ref的值是第一个beanid,propertyname为定义的属性(你要注入的一个类的对象),在PersonServiceBean中一定定义了personDao对象的属性

dao.PersonDaoBean是这样定义的:

package dao;

import impls.PersonDao;

public class PersonDaoBean implements PersonDao {

public void add() {

System.out.println("执行PersonDaoBean中的add方法");

}

}

PersonSeviceBean是这样定义的:

package service;

import impls.PersonDao;

import impls.PersonService;

public class PersonServiceBean implements PersonService {

//属性为PersonDao类对象

    private PersonDao personDao;

    

public PersonDao getPersonDao() {

return personDao;

}

public void setPersonDao(PersonDao personDao) {

this.personDao = personDao;

}

    //重写接口中的save方法

public void save(){

personDao.add();

}

}

11.采用内部bean的方式注入bean

<!-- 采用内部bean的方法 -->

<bean id="personService" class="service.PersonServiceBean">

<property name="personDao">

<bean class="dao.PersonDaoBean"></bean>

</property>

</bean>

12.基本类型数据的bean注入,由property标签控制

<bean id="personDao" class="dao.PersonDaoBean"></bean>

<bean id="personService" class="service.PersonServiceBean">

<property name="personDao" ref="personDao"></property>

<property name="username" value="admin"></property>

</bean> 

业务层这样写:

package service;

import impls.PersonDao;

import impls.PersonService;

public class PersonServiceBean implements PersonService {

//属性为接口PersonDao

private PersonDao personDao;

//定义的基本数据类型,一定要提供get/set方法

    private String username;

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public PersonDao getPersonDao() {

return personDao;

}

public void setPersonDao(PersonDao personDao) {

this.personDao = personDao;

}

    //重写接口中的save方法

public void save(){

personDao.add();

System.out.println("name:"+username);

}

}

 

13.集合类型的注入,也是由property控制:

Set类型:

<bean id="personDao" class="dao.PersonDaoBean"></bean>

<bean id="personService" class="service.PersonServiceBean">

<property name="personDao" ref="personDao"></property>

<property name="username" value="admin"></property>

<property name="id" value="123"></property>

<property name="sets">

<set>

<value>admin1</value>

<value>admin2</value>

<value>admin3</value>

</set>

</property>

</bean>

List类型:

<property name="lists">

<list>

<value>admin4</value>

<value>admin5</value>

<value>admin6</value>

</list>

</property>

map类型:

<property name="maps">

<map>

<entry key="key-1" value="value-1"></entry>

<entry key="key-2" value="value-2"></entry>

<entry key="key-3" value="value-3"></entry>

</map>

</property>

业务层:

package service;

import impls.PersonDao;

import impls.PersonService;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.HashSet;

import java.util.List;

import java.util.Map;

import java.util.Set;

public class PersonServiceBean implements PersonService {

//定义类对象的属性personDao

    private PersonDao personDao;

    //定义基本数据类型username id

    private String username;

private int id;

//定义集合属性sets

private Set<String> sets = new HashSet<String>();

//定义集合属性lists

private List<String> lists = new ArrayList<String>();

//定义属性集合maps

private Map<String,String> maps = new HashMap<String,String>();

public Map<String, String> getMaps() {

return maps;

}

public void setMaps(Map<String, String> maps) {

this.maps = maps;

}

public List<String> getLists() {

return lists;

}

public void setLists(List<String> lists) {

this.lists = lists;

}

public Set<String> getSets() {

return sets;

}

public void setSets(Set<String> sets) {

this.sets = sets;

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public PersonDao getPersonDao() {

return personDao;

}

public void setPersonDao(PersonDao personDao) {

this.personDao = personDao;

}

    //重写接口中的save方法

public void save(){

personDao.add();

System.out.println("name:"+username);

System.out.println("id:"+id);

}

}

客户端调用:

举例:对于map集合

package test;

import impls.PersonService;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {

public static void setUpBeforeClass(){

}

public static void instanceSpring(){

//根据配置文件,创建一个spring容器的实例

ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

//从容器中,根据id,取得对象

PersonService ps =(PersonService)ctx.getBean("personService");

for(String key :ps.getMaps().keySet()){

System.out.println("value:"+ps.getMaps().get(key));

}

}

}

接口申明:

注意:在PersonServiceBean 中实现的是PersonService 接口,所以 ,接口中的定义有取得集合元素的方法:

package impls;

import java.util.List;

import java.util.Map;

import java.util.Set;

public interface PersonService {

public abstract void save();

public Set<String> getSets();

public List<String> getLists();

public Map<String, String> getMaps();

}

对于集合类型都为XXXGet方法,取得集合中的元素值。

构造器注入

14.配置文件:

<bean id="personDao" class="dao.PersonDaoBean"></bean>

<bean id="personService" class="service.PersonServiceBean">

<!-- 利用构造器参数注入 -->

<!-- 为第一个参数注入值 ,ref为要注入的对象 type为接口名-->

<constructor-arg index="0" type="impls.PersonDao" ref="personDao"></constructor-arg>

<!-- 为第二个参数注入值,基本数据类型不用指定type,value为要注入的值 -->

<constructor-arg index="1"  value="xjq"></constructor-arg>

我的理解:构造器注入是,利用constructor属性,类对象用ref,基本数据类型用value指定

业务层:

//演示构造器注入两个属性personDao和username,一定要提供构造器方法

public PersonServiceBean(PersonDao personDao, String username) {

this.personDao = personDao;

this.username = username;

}

//定义类对象的属性personDao

   private PersonDao personDao;

    //定义基本数据类型username

   private String username;

     //重写接口中的save方法

   public void save(){

System.out.println("name:"+username);

personDao.add();

}

}

客户端的调用:

package test;

import impls.PersonService;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {

public static void instanceSpring(){

//根据配置文件,创建一个spring容器的实例

ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

//从容器中,根据id,取得对象

PersonService ps =(PersonService)ctx.getBean("personService");

ps.save();

}

}

最后的输出:

name:xjq

执行PersonDaoBean中的add方法

 

15.有了注解的配置文件:

<?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-2.5.xsd

           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

<context:annotation-config/>        <beanid="personDaoxxxx"class="cn.itcast.dao.impl.PersonDaoBean"></bean>

<beanid="personService"class="cn.itcast.service.impl.PersonServiceBean">

</bean>

</beans>

 

 

 

 

 

 

 

16.利用注解字段的方式,进行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-2.5.xsd

           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

          

          <context:annotation-config/>

          <!--这些bean都是用来定义实体类的-->

          <bean id="personDao" class="dao.PersonDaoBean"></bean>

          <bean id="personService" class="service.PersonServiceBean"></bean>

</beans>

业务层:

@Resource修饰属性

package service;

import impls.PersonDao;

import impls.PersonService;

import javax.annotation.Resource;

public class PersonServiceBean implements PersonService {

//定义类对象的属性personDao

@Resource private PersonDao personDao;

    //定义基本数据类型username id

     private String username;

    //重写接口中的save方法

public void save(){

personDao.add();

}

}

 

17.利用注解setter的方式,进行bean的注入

@Resource修饰set方法

package service;

import impls.PersonDao;

import impls.PersonService;

import javax.annotation.Resource;

public class PersonServiceBean implements PersonService {

//定义类对象的属性personDao

private PersonDao personDao;

     //为字段的set方法加@Resource注解,配置文件不变

@Resource

    public void setPersonDao(PersonDao personDao) {

this.personDao = personDao;

}

//定义基本数据类型username id

    private String username;

    //重写接口中的save方法

public void save(){

personDao.add();

}

}

 

18.利用@Autowired进行依赖注入

是一种按照类型进行装配

业务层:

@Autowired利用该注释修饰属性

package service;

import impls.PersonDao;

import impls.PersonService;

import org.springframework.beans.factory.annotation.Autowired;

public class PersonServiceBean implements PersonService {

//定义类对象的属性personDao

@Autowired private PersonDao personDao;

    public void setPersonDao(PersonDao personDao) {

this.personDao = personDao;

}

    //重写接口中的save方法

public void save(){

personDao.add();

}

}

配置文件:

<?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-2.5.xsd

           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

          

          <context:annotation-config/>

          

          <bean id="personDao" class="dao.PersonDaoBean"></bean>

          <bean id="personService" class="service.PersonServiceBean"></bean>

</beans>

 

19.自动装配,但是不推荐,会有很多意外的情况

 

20.AOP技术

 

 

 

 

 

 

自己利用jdk编写:

目标类接口:

package aop;

public interface PersonService {

public void save(String name);

public void update(String name,Integer personId);

public String getPersonName(Integer personId);

}

业务层:

package aop_service;

import aop.PersonService;

//业务层:PersonServiceBean

/*

 * 拦截用户对方法的请求

 * 判断用户是否有权限(user是否为null)执行业务方法

 * 有则执行,没有的话就不执行

 *

 * */

public class PersonServiceBean implements PersonService {

//定义一个用户user

private String user = null;

public String getUser() {

return user;

}

//构造器

    public PersonServiceBean(String user) {

this.user = user;

}

public PersonServiceBean() {

super();

// TODO Auto-generated constructor stub

}

public void save(String name) {

// TODO Auto-generated method stub

System.out.println("我是save方法");

}

public void update(String name, Integer personId) {

// TODO Auto-generated method stub

System.out.println("我是update方法");

}

public String getPersonName(Integer personId) {

// TODO Auto-generated method stub

return "admin";

}

}

代理工厂:

package aop_service;

import java.lang.reflect.Method;

import java.lang.reflect.Proxy;

public class JDKProxyFactory implements java.lang.reflect.InvocationHandler {

//定义一个目标对象

private Object targetObject;

//创建代理实例

public Object createProxyInstance(Object targetObject){

this.targetObject=targetObject;

return Proxy.newProxyInstance(this.targetObject.getClass().getClassLoader(),

this.targetObject.getClass().getInterfaces(),this);

}

//返回一个代理对象

public Object invoke(Object proxy, Method method, Object[] args)

throws Throwable {

// TODO Auto-generated method stub

PersonServiceBean bean = (PersonServiceBean) this.targetObject;

Object result = null;

if(bean.getUser()!=null){

result = method.invoke(targetObject, args);

}

return result;

}

}

测试:

package test;

import aop.PersonService;

import aop_service.JDKProxyFactory;

import aop_service.PersonServiceBean;

public class aopTest {

public static void main(String[] args) {

// TODO Auto-generated method stub

//创建代理工厂

JDKProxyFactory ff = new JDKProxyFactory();

//返回代理对象

PersonService ps = (PersonService)ff.createProxyInstance(new PersonServiceBean("xxx"));

ps.save("888");

}

}

 

21.利用spring进行aop开发

前置通知 后置通知  最终通知 环绕通知 异常通知

一定要引入的jar包:

 

配置文件:

<?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" 

       xmlns:aop="http://www.springframework.org/schema/aop"      

       xsi:schemaLocation="http://www.springframework.org/schema/beans

           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd

           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

        <aop:aspectj-autoproxy/>

        <!-- 将切面类交给spring容器去管理 -->

        <bean id="myInterceptor" class="aop.MyInterceptor"/>

        <!-- 将业务bean也交给spring管理 -->

        <bean id="personService" class="aop_service.PersonServiceBean"></bean>

</beans>

利用注解的方法进行:

切面类和切入点的定义:

package aop;

import org.aspectj.lang.annotation.AfterReturning;

import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.annotation.Before;

import org.aspectj.lang.annotation.Pointcut;

//申明该类为一个切面 ,该切面应该交由spring容器进行管理,基于xml配置去管理

@Aspect 

public class MyInterceptor {

//申明一个切入点

@SuppressWarnings("unused")

@Pointcut("execution(* aop_service.PersonServiceBean.*(..))")

private void anyMethod(){}

//在执行业务方法前,前置通知

@Before("anyMethod()")

public void doAccessCheck(){

System.out.println("前置通知");

}

//在执行业务方法后,后置通知

@AfterReturning("anyMethod()")

public void doAfterReturning(){

System.out.println("后置通知");

}

      //最终的通知

@After("anyMethod()")

public void doAfter(){

System.out.println("最终通知");

}

}

业务层:

package aop_service;

import aop.PersonService;

//业务层:PersonServiceBean

/*

 * 拦截用户对方法的请求

 * 判断用户是否有权限(user是否为null)执行业务方法

 * 有则执行,没有的话就不执行

 *

 * */

public class PersonServiceBean implements PersonService {

public void save(String name) {

// TODO Auto-generated method stub

System.out.println("我是save方法");

}

public void update(String name, Integer personId) {

// TODO Auto-generated method stub

System.out.println("我是update方法");

}

public String getPersonName(Integer personId) {

// TODO Auto-generated method stub

System.out.println("我是getPersonName方法");

return "admin";

}

}

测试类:

package test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import aop.PersonService;

public class SpringAopTest {

public static void main(String[] args) {

// TODO Auto-generated method stub

//创建spring容器

ApplicationContext cxt = new ClassPathXmlApplicationContext("beans.xml");

//容器先取得业务层的bean

PersonService ps = (PersonService)cxt.getBean("personService");

//调用业务层对象的save方法

ps.save("xxx");

}

}

输出:

 

 

 

22.环绕通知

//环绕通知

@Around("anyMethod()")

public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable{

System.out.println("进入方法");

Object result  = pjp.proceed();

System.out.println("退出方法");

return result;

}

 

环绕通知经常可以用于权限控制

23.利用xml进行配置aop

配置文件:

<?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"

xmlns:aop="http://www.springframework.org/schema/aop"

xsi:schemaLocation="http://www.springframework.org/schema/beans

           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd

           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

<aop:aspectj-autoproxy />

<!-- 将业务bean也交给spring管理 -->

<bean id="personService" class="aop_service.PersonServiceBean"></bean>

     <!-- 将拦截对象交给  spring管理-->

<bean id="aspetbean" class="aop.MyInterceptor"></bean>

<aop:config>

<aop:aspect id="asp" ref="aspetbean">

<aop:pointcut id="mycut"

expression="execution(* aop_service.PersonServiceBean.*(..))"/>

<aop:before pointcut-ref="mycut" method="doAccessCheck" />

</aop:aspect>

</aop:config>

</beans>

业务层:拦截bean,是一个普通的类对象

package aop;

import org.aspectj.lang.ProceedingJoinPoint;

//申明该类为一个切面 ,该切面应该交由spring容器进行管理,基于xml配置去管理

public class MyInterceptor {

//在执行业务方法前,前置通知

public void doAccessCheck(){

System.out.println("前置通知");

}

//在执行业务方法后,后置通知

public void doAfterReturning(){

System.out.println("后置通知");

}

//最终的通知

public void doAfter(){

System.out.println("最终通知");

}

//环绕通知

public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable{

System.out.println("进入方法");

Object result  = pjp.proceed();

System.out.println("退出方法");

return result;

}

}

普通的业务类对象:

package aop_service;

import aop.PersonService;

public class PersonServiceBean implements PersonService {

public void save(String name) {

// TODO Auto-generated method stub

System.out.println("我是save方法");

}

public void update(String name, Integer personId) {

// TODO Auto-generated method stub

System.out.println("我是update方法");

}

public String getPersonName(Integer personId) {

// TODO Auto-generated method stub

System.out.println("我是getPersonName方法");

return "admin";

}

}

测试文件:

package test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import aop.PersonService;

 

public class SpringAopTest {

public static void main(String[] args) {

// TODO Auto-generated method stub

//创建spring容器

ApplicationContext cxt = new ClassPathXmlApplicationContext("beans.xml");

//容器先取得业务层的bean

PersonService ps = (PersonService)cxt.getBean("personService");

//调用业务层对象的save方法

ps.save("xxx");

}

}

 

24.expression="execution(* aop_service.PersonServiceBean.*(..))的理解

返回值类型为所有类型 用 .  表示 ,可以拦截aop_service包下的PersonServiceBean类的所有的方法,参数类型为所有的类型,. . 表示。

!可以取反     !void  拦截不是void类型的

25.aop适合权限系统的使用

26.spring+jdbc组合开发

beans.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"

xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="http://www.springframework.org/schema/beans

           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd

           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd

           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <!-- 启用占位符,配置数据库连接 -->

<context:property-placeholder location="classpath:jdbc.properties" />

<!-- 控制数据连接 -->

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"

destroy-method="close">

<property name="driverClassName" value="${driverClassName}" />

<property name="url" value="${url}" />

<property name="username" value="${username}" />

<property name="password" value="${password}" />

<!-- 连接池启动时的初始值 -->

<property name="initialSize" value="${initialSize}" />

<!-- 连接池的最大值 -->

<property name="maxActive" value="${maxActive}" />

<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->

<property name="maxIdle" value="${maxIdle}" />

<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->

<property name="minIdle" value="${minIdle}" />

</bean>

<!-- 事务管理器 -->

<bean id="txManager"

class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<property name="dataSource" ref="dataSource" />

</bean>

<!-- 对注解进行解析没,需要指定一个事务管理器 -->

<tx:annotation-driven transaction-manager="txManager" />

    <!-- 基于xml将dataSource属性注入 -->

<bean id="personService" class="JDBCSpring.PersonServiceBean">

<property name="dataSource" ref="dataSource" />

</bean>

</beans>

数据库配置的属性文件jdbc.properties

driverClassName=org.gjt.mm.mysql.Driver

url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF-8

username=root

password=

initialSize=1

maxActive=500

maxIdle=2

minIdle=1

业务类:

package JDBCSpring;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import bean.Person;

public class PersonServiceBean implements JDBCSpring.PersonService {

private JdbcTemplate jdbcTemplate;

public void setDataSource(DataSource dataSource) {

this.jdbcTemplate = new JdbcTemplate(dataSource);

}

public void delete(Integer personid) {

jdbcTemplate.update("delete from person where id=?", new Object[]{personid},

new int[]{java.sql.Types.INTEGER});

}

public Person getPerson(Integer personid) {

/*return (Person)jdbcTemplate.queryForObject("select * from person where id=?", new Object[]{personid},

new int[]{java.sql.Types.INTEGER}, new PersonRowMapper());*/

return null;

}

public List<Person> getPersons() {

//return (List<Person>)jdbcTemplate.query("select * from person", new PersonRowMapper());

   return null;

}

public void save(Person person) {

jdbcTemplate.update("insert into person(name) values(?)", new Object[]{person.getName()},

new int[]{java.sql.Types.VARCHAR});

}

public void update(Person person) {

jdbcTemplate.update("update person set name=? where id=?", new Object[]{person.getName(), person.getId()},

new int[]{java.sql.Types.VARCHAR, java.sql.Types.INTEGER});

}

}

实例类:

package bean;

public class Person {

public Person(String name) {

this.name = name;

}

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

private Integer id;

private String name;

}

 

 

测试类:

package JDBCSpring;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import bean.Person;

public class jdbcTest {

public static void main(String[] args) {

ApplicationContext act = new ClassPathXmlApplicationContext("beans.xml");

PersonService ps = (PersonService) act.getBean("personService");

ps.save(new Person("haha"));

System.out.println("ok!");

}

}

 

带着热忱学技术,带着耐心做技术,带着分享去交流,带着微笑探我们的程序人生!
原文地址:https://www.cnblogs.com/jiaqingshareing/p/5677233.html