Spring 框架学习

Spring 复习

[toc]

spring介绍

三层架构中spring位置,连接三层。


  • spring一站式框架
    • 正是因为spring框架性质是属于容器性质的.
    • 容器中装什么对象就有什么功能.所以可以一站式.例如:容器中有 http 对象,那么就能操作请求响应,容器中有 数据库 对象,那么就能操作数据库。
    • 不仅不排斥其他框架,还能帮其他框架管理对象.
    • aop支持
    • ioc思想'
    • spring jdbc
    • aop 事务
    • junit 测试支持



spring 入门搭建

1.导包

日志包


com.springsource.org.apache.log4j-1.2.15.jar(可选,老版本可能需要这个包)

2.创建一个对象

3.书写配置注册对象到容器

位置任意(建议放到src下),配置文件名任意(建议applicationContext.xml)

4.代码测试



IOC

概念

IoC -- Inverse of Control,控制反转,将对象的创建权反转给Spring!!

以前的对象都是开发人员手动创建和维护,包括依赖关系也是自己注入。

DI -- Dependency Injection,依赖注入。

实现 IOC 思想需要 DI 做支持。
在Spring框架负责创建Bean对象时,动态的将依赖对象注入到Bean组件中。

  1. ApplicationContext接口

    • 使用ApplicationContext工厂的接口,使用该接口可以获取到具体的Bean对象
    • 该接口下有两个具体的实现类
      • ClassPathXmlApplicationContext -- 加载类路径下的Spring配置文件
      • FileSystemXmlApplicationContext -- 加载本地磁盘下的Spring配置文件
  2. BeanFactory工厂(是Spring框架早期的创建Bean对象的工厂接口)

    • 使用BeanFactory接口也可以获取到Bean对象

BeanFactory和ApplicationContext的区别

  • BeanFactory -- BeanFactory采取延迟加载,第一次getBean时才会初始化Bean

  • ApplicationContext -- 在加载applicationContext.xml时候就会创建具体的Bean对象的实例,还提供了一些其他的功能。

    • 事件传递
    • Bean自动装配
    • 各种不同应用层的Context实现

结论:

web开发中,使用applicationContext. 在资源匮乏的环境可以使用BeanFactory.



spring配置详解

Bean元素

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">


    <!-- 将User对象交给spring容器管理 -->
    <!-- Bean元素:使用该元素描述需要spring容器管理的对象
            class属性:被管理对象的完整类名.
            name属性:给被管理的对象起个名字.获得对象时根据该名称获得对象.  
                    可以重复.可以使用特殊字符.
            id属性: 与name属性一模一样. 
                    名称不可重复.不能使用特殊字符.
            结论: 尽量使用name属性.
      -->
    <bean  name="user" class="cn.itcast.bean.User" ></bean>
</beans>

Bean元素进阶

scope属性

  • singleton(默认值):单例对象.被标识为单例的对象在spring容器中只会存在一个实例
  • prototype:多例原型.被标识为多例的对象,每次再获得才会创建.每次创建都是新的对象.整合struts2时,ActionBean必须配置为多例的.
  • request:web环境下.对象与request生命周期一致.
  • session:web环境下,对象与session生命周期一致.

生命周期属性

  • init-method

    配置一个方法作为生命周期初始化方法.spring会在对象创建之后立即调用.

  • destory-method

    配置一个方法作为生命周期的销毁方法.spring容器在关闭并销毁所有容器中的对象之前调用.


spring创建对象的方式

  1. 空参构造方式


  2. 静态工厂(了解)



  1. 实例工厂(了解)



spring的分模块配置



spring属性注入

注入方式

set方法注入

<!-- set方式注入: -->
<bean  name="user" class="cn.itcast.bean.User" >
    <!--值类型注入: 为User对象中名为name的属性注入tom作为值 -->
    <property name="name" value="tom" ></property>
    <property name="age"  value="18" ></property>
    <!-- 引用类型注入: 为car属性注入下方配置的car对象 -->
    <property name="car"  ref="car" ></property>
</bean>

<!-- 将car对象配置到容器中 -->
<bean name="car" class="cn.itcast.bean.Car" >
    <property name="name" value="兰博基尼" ></property>
    <property name="color" value="黄色" ></property>
</bean>

构造函数注入

public class User {
    private String name;
    private Integer age;
    private Car car;
    
    public User(String name, Car car) {
        System.out.println("User(String name, Car car)!!");
        this.name = name;
        this.car = car;
    }
。。。
} 


<!-- 构造函数注入 -->
<bean name="user2" class="cn.itcast.bean.User" >
    <!-- name属性: 构造函数的参数名 -->
    <!-- index属性: 构造函数的参数索引,房子多个相同类型的参数,用于区分 -->
    <!-- type属性: 构造函数的参数类型-->
    <constructor-arg name="name" index="0" type="java.lang.Integer" value="999"  ></constructor-arg>
    <constructor-arg name="car" ref="car" index="1" ></constructor-arg>
</bean>

p名称空间注入

<!-- p名称空间注入, 走set方法
1.导入P名称空间  xmlns:p="http://www.springframework.org/schema/p"
2.使用p:属性完成注入
    |-值类型: p:属性名="值"
    |-对象类型: p:属性名-ref="bean名称"
 -->
<bean  name="user3" class="cn.itcast.bean.User" p:name="jack" p:age="20" p:car-ref="car"  >
</bean>

spel注入

<!-- 
    spel注入: spring Expression Language sping表达式语言
    #{user.name} 表示上面的 user 的 《bean name 属性》
 -->
<bean  name="user4" class="cn.itcast.bean.User" >
        <property name="name" value="#{user.name}" ></property>
        <property name="age" value="#{user3.age}" ></property>
        <property name="car" ref="car" ></property>
</bean>

复杂类型注入

数组

<!-- 如果数组中只准备注入一个值(对象),直接使用value|ref即可 
<property name="arr" value="tom" ></property>
-->
<!-- array注入,多个元素注入 -->
<property name="arr">
    <array>
        <value>tom</value>
        <value>jerry</value>
        <ref bean="user4" />
    </array>
</property>

List

<!-- 如果List中只准备注入一个值(对象),直接使用value|ref即可 
<property name="list" value="jack" ></property>-->
<property name="list"  >
    <list>
        <value>jack</value>
        <value>rose</value>
        <ref bean="user3" />
    </list>
</property>

Map

<!-- map类型注入 -->
<property name="map"  >
    <map>
        <entry key="url" value="jdbc:mysql:///crm" ></entry>
        <entry key="user" value-ref="user4"  ></entry>
        <entry key-ref="user3" value-ref="user2"  ></entry>
    </map> 
</property>

Properties

<!-- prperties 类型注入 -->
<property name="prop"  >
    <props>
        <prop key="driverClass">com.jdbc.mysql.Driver</prop>
        <prop key="userName">root</prop>
        <prop key="password">1234</prop>
    </props>
</property>



使用注解配置spring

步骤

导包4+2+spring-aop

  1. 为主配置文件引入新的命名空间(约束)
  2. 开启使用注解代理配置文件


  3. 在类中使用注解配置

类中使用注解配置

将对象注册到容器
//<bean name="user" class="cn.itcast.bean.User"/> = @Component("user")
//@Component("user") //早期使用
//@Service("user") // service层
//@Controller("user") // web层
//@Repository("user")// dao层
public class User {
    private String name;
    private Integer age;
    private Car car;
    
    public Car getCar() {
        return car;
    }
修改对象的作用范围
//指定对象的作用范围
@Scope(scopeName="singleton")
public class User {
值类型注入

通过反射的Field赋值,破坏了封装性

@Value("18")
private Integer age;

通过set方法赋值,推荐使用.

@Value("tom")   
public void setName(String name) {
    this.name = name;
}
引用类型注入
@Autowired //自动装配
private Car car;

默认找同名的装配上

@Autowired //自动装配
//问题:如果匹配多个类型一致的对象.将无法选择具体注入哪一个对象.
@Qualifier("car2")//使用@Qualifier注解告诉spring容器自动装配哪个名称的对象
private Car car;

当多个对象是同一个类,需要指定某个对象,@Autowired + @Qualifier()

@Resource(name="car")//手动注入,指定注入哪个名称的对象
private Car car;

当多个对象是同一个类,需要指定某个对象,@Resource()

初始化和销毁方法
@Repository("user")
public class User {
    private String name;
    
    @Value("18")
    private Integer age;
    ... ...
    
    @PostConstruct //在对象被创建后调用.init-method
    public void init(){
        System.out.println("我是初始化方法!");
    }
    @PreDestroy //在销毁之前调用.destory-method
    public void destory(){
        System.out.println("我是销毁方法!");
    }
}

spring与junit整合测试

  1. 导包

  2. 配置注解

    //帮我们创建容器
    @RunWith(SpringJUnit4ClassRunner.class)
    //指定创建容器时使用哪个配置文件
    @ContextConfiguration("classpath:applicationContext.xml")
    public class Demo {
        
        //将名为user的对象注入到u变量中
        @Resource(name="user")
        private User u;
        
        @Test
        public void fun1(){
            System.out.println(u);
        }
    }
    
  3. 测试



spring中的aop

aop思想介绍



spring中的aop概念

spring实现aop的原理

  • 动态代理(优先)
    被代理对象必须要实现接口,才能产生代理对象.如果没有接口将不能使用动态代理技术
  • cglib代理(没有接口)
    第三方代理技术,cglib代理.可以对任何类生成代理.代理的原理是对目标对象进行继承代理. 如果目标对象被final修饰.那么该类无法被cglib代理.

aop名词学习



spring中的aop演示

xml配置(步骤)

  1. 导包4+2

    • spring的aop包
      • spring-aspects-4.2.4.RELEASE.jar
      • spring-aop-4.2.4.RELEASE.jar
    • spring需要第三方aop包
      • com.springsource.org.aopalliance-1.0.0.jar
      • com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
  2. 准备目标对象

    public class UserServiceImpl implements UserService {
        @Override
        public void save() {
            System.out.println("保存用户!");
            //int i = 1/0;
        }
        @Override
        public void delete() {
            System.out.println("删除用户!");
        }
        @Override
        public void update() {
            System.out.println("更新用户!");
        }
        @Override
        public void find() {
            System.out.println("查找用户!");
        }
    }
    
  3. 准备通知

    //通知类
    public class MyAdvice {
        
        //前置通知  
    //      |-目标方法运行之前调用
        //后置通知(如果出现异常不会调用)
    //      |-在目标方法运行之后调用
        //环绕通知
    //      |-在目标方法之前和之后都调用
        //异常拦截通知
    //      |-如果出现异常,就会调用
        //后置通知(无论是否出现 异常都会调用)
    //      |-在目标方法运行之后调用
    //----------------------------------------------------------------
        //前置通知
        public void before(){
            System.out.println("这是前置通知!!");
        }
        //后置通知
        public void afterReturning(){
            System.out.println("这是后置通知(如果出现异常不会调用)!!");
        }
        //环绕通知
        public Object around(ProceedingJoinPoint pjp) throws Throwable {
            System.out.println("这是环绕通知之前的部分!!");
            Object proceed = pjp.proceed();//调用目标方法
            System.out.println("这是环绕通知之后的部分!!");
            return proceed;
        }
        //异常通知
        public void afterException(){
            System.out.println("出事啦!出现异常了!!");
        }
        //后置通知
        public void after(){
            System.out.println("这是后置通知(出现异常也会调用)!!");
        }
    }
    
  4. 配置进行织入,将通知织入目标对象中

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd ">
    
    <!-- 准备工作: 导入aop(约束)命名空间 -->
    <!-- 1.配置目标对象 -->
        <bean name="userService" class="cn.itcast.service.UserServiceImpl" ></bean>
    <!-- 2.配置通知对象 -->
        <bean name="myAdvice" class="cn.itcast.d_springaop.MyAdvice" ></bean>
    <!-- 3.配置将通知织入目标对象 -->
        <aop:config>
            <!-- 配置切入点 
                public void cn.itcast.service.UserServiceImpl.save() 
                void cn.itcast.service.UserServiceImpl.save()
                * cn.itcast.service.UserServiceImpl.save()
                * cn.itcast.service.UserServiceImpl.*()
                
                * cn.itcast.service.*ServiceImpl.*(..)
                * cn.itcast.service..*ServiceImpl.*(..)
            -->
            <aop:pointcut expression="execution(* cn.itcast.service.*ServiceImpl.*(..))" id="pc"/>
            <aop:aspect ref="myAdvice" >
                <!-- 指定名为before方法作为前置通知 -->
                <aop:before method="before" pointcut-ref="pc" />
                <!-- 后置 -->
                <aop:after-returning method="afterReturning" pointcut-ref="pc" />
                <!-- 环绕通知 -->
                <aop:around method="around" pointcut-ref="pc" />
                <!-- 异常拦截通知 -->
                <aop:after-throwing method="afterException" pointcut-ref="pc"/>
                <!-- 后置 -->
                <aop:after method="after" pointcut-ref="pc"/>
            </aop:aspect>
        </aop:config>
    </beans>
    
  5. 测试:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:cn/itcast/d_springaop/applicationContext.xml")
    public class Demo {
        @Resource(name="userService")
        private UserService us;
        
        @Test
        public void fun1(){
            us.save();
        }
        
    }
    

注解配置(步骤)

  1. 导包4+2

    • spring的aop包
      • spring-aspects-4.2.4.RELEASE.jar
      • spring-aop-4.2.4.RELEASE.jar
    • spring需要第三方aop包
      * com.springsource.org.aopalliance-1.0.0.jar
      * com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
  2. 准备目标对象

    public class UserServiceImpl implements UserService {
        @Override
        public void save() {
            System.out.println("保存用户!");
            //int i = 1/0;
        }
        @Override
        public void delete() {
            System.out.println("删除用户!");
        }
        @Override
        public void update() {
            System.out.println("更新用户!");
        }
        @Override
        public void find() {
            System.out.println("查找用户!");
        }
    }
    
  3. 准备通知

    //通知类
    @Aspect
    //表示该类是一个通知类
    public class MyAdvice {
        
        //抽取出来,同一管理,也可以在下面每个注解中复制一遍。
        @Pointcut("execution(* cn.itcast.service.*ServiceImpl.*(..))")
        public void pc(){}
        
        //前置通知
        //指定该方法是前置通知,并制定切入点
        @Before("MyAdvice.pc()")
        public void before(){
            System.out.println("这是前置通知!!");
        }
        //后置通知
        @AfterReturning("execution(* cn.itcast.service.*ServiceImpl.*(..))")
        public void afterReturning(){
            System.out.println("这是后置通知(如果出现异常不会调用)!!");
        }
        //环绕通知
        @Around("execution(* cn.itcast.service.*ServiceImpl.*(..))")
        public Object around(ProceedingJoinPoint pjp) throws Throwable {
            System.out.println("这是环绕通知之前的部分!!");
            Object proceed = pjp.proceed();//调用目标方法
            System.out.println("这是环绕通知之后的部分!!");
            return proceed;
        }
        //异常通知
        @AfterThrowing("execution(* cn.itcast.service.*ServiceImpl.*(..))")
        public void afterException(){
            System.out.println("出事啦!出现异常了!!");
        }
        //后置通知
        @After("execution(* cn.itcast.service.*ServiceImpl.*(..))")
        public void after(){
            System.out.println("这是后置通知(出现异常也会调用)!!");
        }
    }
    
  4. 配置进行织入,将通知织入目标对象中

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd ">
    
    <!-- 准备工作: 导入aop(约束)命名空间 -->
    <!-- 1.配置目标对象 -->
        <bean name="userService" class="cn.itcast.service.UserServiceImpl" ></bean>
    <!-- 2.配置通知对象 -->
        <bean name="myAdvice" class="cn.itcast.e_annotationaop.MyAdvice" ></bean>
    <!-- 3.开启使用注解完成织入 -->
        <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    
    </beans>
    



spring整合JDBC

spring提供了很多模板整合Dao技术


spring中提供了一个可以操作数据库的对象.对象封装了jdbc技术.

JDBCTemplate => JDBC模板对象
与DBUtils中的QueryRunner非常相似.

步骤

  1. 导包

    • 4+2
    • spring-test
    • spring-aop
    • junit4类库
    • c3p0连接池
    • JDBC驱动
    • spring-jdbc
    • spring-tx事务
  2. 准备数据库


  3. 书写Dao

    public interface UserDao {
    
        //增
        void save(User u);
        //删
        void delete(Integer id);
        //改
        void update(User u);
        //查询单个对象
        User getById(Integer id);
        //查询值类型
        int getTotalCount();
        //查询list集合类型
        List<User> getAll();
    }
    
    
    
    //使用JDBC模板实现增删改查
    public class UserDaoImpl implements UserDao {
    
    private JdbcTemplate jdbcTemplate;
    
        @Override
        public void save(User u) {
            String sql = "insert into t_user values(null,?) ";
            jdbcTemplate.update(sql, u.getName());
        }
        @Override
        public void delete(Integer id) {
            String sql = "delete from t_user where id = ? ";
            jdbcTemplate.update(sql,id);
        }
        @Override
        public void update(User u) {
            String sql = "update  t_user set name = ? where id=? ";
            jdbcTemplate.update(sql, u.getName(),u.getId());
        }
        @Override
        public User getById(Integer id) {
            String sql = "select * from t_user where id = ? ";
            return jdbcTemplate.queryForObject(sql,new RowMapper<User>(){
                @Override
                public User mapRow(ResultSet rs, int arg1) throws SQLException {
                    User u = new User();
                    u.setId(rs.getInt("id"));
                    u.setName(rs.getString("name"));
                    return u;
                }}, id);
            
        }
        @Override
        public int getTotalCount() {
            String sql = "select count(*) from t_user  ";
            Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
            return count;
        }
    
        @Override
        public List<User> getAll() {
            String sql = "select * from t_user  ";
            List<User> list = jdbcTemplate.query(sql, new RowMapper<User>(){
                @Override
                public User mapRow(ResultSet rs, int arg1) throws SQLException {
                    User u = new User();
                    u.setId(rs.getInt("id"));
                    u.setName(rs.getString("name"));
                    return u;
                }});
            return list;
        }
    }
    
  1. spring配置

    db.properties

    jdbc.jdbcUrl=jdbc:mysql:///hibernate_32
    jdbc.driverClass=com.mysql.jdbc.Driver
    jdbc.user=root
    jdbc.password=1234
    

    applicationContext.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd ">
    
        <!-- 指定spring读取db.properties配置 -->
        <context:property-placeholder location="classpath:db.properties"  />
        
        <!-- 1.将连接池放入spring容器 -->
        <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
            <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
            <property name="driverClass" value="${jdbc.driverClass}" ></property>
            <property name="user" value="${jdbc.user}" ></property>
            <property name="password" value="${jdbc.password}" ></property>
        </bean>
        
        
        <!-- 2.将JDBCTemplate放入spring容器 -->
        <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
            <property name="dataSource" ref="dataSource" ></property>
        </bean>
        
        <!-- 3.将UserDao放入spring容器 -->
        <bean name="userDao" class="cn.itcast.a_jdbctemplate.UserDaoImpl" >
            <property name="jt" ref="jdbcTemplate" ></property>
        </bean>
    
    </beans>
    
  2. 测试

    //演示JDBC模板
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:applicationContext.xml")
    public class Demo {
            @Resource(name="userDao")
        private UserDao ud;
        
        @Test
        public void fun1() throws Exception{
            
            //0 准备连接池
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            dataSource.setDriverClass("com.mysql.jdbc.Driver");
            dataSource.setJdbcUrl("jdbc:mysql:///hibernate_32");
            dataSource.setUser("root");
            dataSource.setPassword("1234");
            //1 创建JDBC模板对象
            JdbcTemplate jt = new JdbcTemplate();
            jt.setDataSource(dataSource);
            //2 书写sql,并执行
            String sql = "insert into t_user values(null,'rose') ";
            jt.update(sql);
            
        }
        
        @Test
        public void fun2() throws Exception{
            User u = new User();
            u.setName("tom");
            ud.save(u);
        }
        @Test
        public void fun3() throws Exception{
            User u = new User();
            u.setId(2);
            u.setName("jack");
            ud.update(u);
            
        }
        
        @Test
        public void fun4() throws Exception{
            ud.delete(2);
        }
        
        @Test
        public void fun5() throws Exception{
            System.out.println(ud.getTotalCount());
        }
        
        @Test
        public void fun6() throws Exception{
            System.out.println(ud.getById(1));
        }
        
        @Test
        public void fun7() throws Exception{
            System.out.println(ud.getAll());
        }
    }
    

进阶内容(了解)

JDBCDaoSupport

使用:extends JdbcDaoSupport

//使用JDBC模板实现增删改查
public class UserDaoImpl extends JdbcDaoSupport implements UserDao {
    @Override
    public void save(User u) {
        String sql = "insert into t_user values(null,?) ";
        super.getJdbcTemplate().update(sql, u.getName());
    }
    @Override
    public void delete(Integer id) {
        String sql = "delete from t_user where id = ? ";
        super.getJdbcTemplate().update(sql,id);
    }
    @Override
    public void update(User u) {
        String sql = "update  t_user set name = ? where id=? ";
        super.getJdbcTemplate().update(sql, u.getName(),u.getId());
    }
    @Override
    public User getById(Integer id) {
        String sql = "select * from t_user where id = ? ";
        return super.getJdbcTemplate().queryForObject(sql,new RowMapper<User>(){
            @Override
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                User u = new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                return u;
            }}, id);
        
    }
    @Override
    public int getTotalCount() {
        String sql = "select count(*) from t_user  ";
        Integer count = super.getJdbcTemplate().queryForObject(sql, Integer.class);
        return count;
    }

    @Override
    public List<User> getAll() {
        String sql = "select * from t_user  ";
        List<User> list = super.getJdbcTemplate().query(sql, new RowMapper<User>(){
            @Override
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                User u = new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                return u;
            }});
        return list;
    }
}

不用将JDBCTemplate放入spring容器

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd ">

    <!-- 指定spring读取db.properties配置 -->
    <context:property-placeholder location="classpath:db.properties"  />
    
    <!-- 1.将连接池放入spring容器 -->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
        <property name="driverClass" value="${jdbc.driverClass}" ></property>
        <property name="user" value="${jdbc.user}" ></property>
        <property name="password" value="${jdbc.password}" ></property>
    </bean>
    
    
    <!-- 3.将UserDao放入spring容器 -->
    <bean name="userDao" class="cn.itcast.a_jdbctemplate.UserDaoImpl" >
        <property name="dataSource" ref="dataSource" ></property>
    </bean>
    
</beans>



spring中aop事务

事务

  • 事务特性:acid
  • 事务并发问题
    • 脏读
    • 不可重复读
    • 幻读
    • 事务的隔离级别
      • 1 读未提交
      • 2 读已提交
      • 4 可重复读
      • 8 串行化

spring封装了事务管理代码

  • 事务操作
    • 打开事务
    • 提交事务
    • 回滚事务
  • 事务操作对象
    • 因为在不同平台,操作事务的代码各不相同.spring提供了一个接口

    • PlatformTransactionManager 接口

      • DataSourceTransactionManager
      • HibernateTransitionmanager

      注意:在spring中玩事务管理.最为核心的对象就是TransactionManager对象

    • spring管理事务的属性介绍

      • 事务的隔离级别
        • 1 读未提交
        • 2 读已提交
        • 4 可重复读
        • 8 串行化
      • 是否只读
        • true 只读
        • false 可操作
      • 事务的传播行为
        PROPAGION_XXX :事务的传播行为
        • 保证同一个事务中
          • PROPAGATION_REQUIRED 支持当前事务,如果不存在 就新建一个。(默认)
          • PROPAGATION_SUPPORTS 支持当前事务,如果不存在,就不使用事务。
          • PROPAGATION_MANDATORY 支持当前事务,如果不存在,抛出异常。
        • 保证没有在同一个事务中
          • PROPAGATION_REQUIRES_NEW 如果有事务存在,挂起当前事务,创建一个新的事务。
          • PROPAGATION_NOT_SUPPORTED 以非事务方式运行,如果有事务存在,挂起当前事务。
          • PROPAGATION_NEVER 以非事务方式运行,如果有事务存在,抛出异常 PROPAGATION_NESTED 如果当前事务存在,则嵌套事务执行。

spring管理事务方式

编码式

  1. 将核心事务管理器配置到spring容器


  2. 配置TransactionTemplate模板


  3. 将事务模板注入Service


  4. 在Service中调用模板



    这样每个事务的方法都要写这个方法(麻烦),了解即可,一般不用这种方式。

xml配置(aop) 重点

  1. 导包

    • aop
    • aspect
    • aop联盟
    • weaving织入包
  2. 基本配置

    • beans: 最基本
    • context:读取properties配置
    • aop:配置aop
    • tx:配置事务通知
  3. 配置通知 和 配置将通知织入目标

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
    
        <!-- 指定spring读取db.properties配置 -->
        <context:property-placeholder location="classpath:db.properties"  />
        
        <!-- 事务核心管理器,封装了所有事务操作. 依赖于连接池 -->
        <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
            <property name="dataSource" ref="dataSource" ></property>
        </bean>
        <!-- 事务模板对象 -->
        <bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate" >
            <property name="transactionManager" ref="transactionManager" ></property>
        </bean>
        
        <!-- 配置事务通知 -->
        <tx:advice id="txAdvice" transaction-manager="transactionManager" >
            <tx:attributes>
                <!-- 以方法为单位,指定方法应用什么事务属性
                    isolation:隔离级别
                    propagation:传播行为
                    read-only:是否只读
                 -->
                <tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
                <tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
                <tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
                <tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
                <tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
                <tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
                <tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
                <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
                <tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
            </tx:attributes>
        </tx:advice>
        
        
        <!-- 配置织入 -->
        <aop:config  >
            <!-- 配置切点表达式 -->
            <aop:pointcut expression="execution(* cn.itcast.service.*ServiceImpl.*(..))" id="txPc"/>
            <!-- 配置切面 : 通知+切点
                    advice-ref:通知的名称
                    pointcut-ref:切点的名称
             -->
            <aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" />
        </aop:config>
        
        
        <!-- 1.将连接池 -->
        <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
            <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
            <property name="driverClass" value="${jdbc.driverClass}" ></property>
            <property name="user" value="${jdbc.user}" ></property>
            <property name="password" value="${jdbc.password}" ></property>
        </bean>
        
        
        
        <!-- 2.Dao-->
        <bean name="accountDao" class="cn.itcast.dao.AccountDaoImpl" >
            <property name="dataSource" ref="dataSource" ></property>
        </bean>
        <!-- 3.Service-->
        <bean name="accountService" class="cn.itcast.service.AccountServiceImpl" >
            <property name="ad" ref="accountDao" ></property>
            <property name="tt" ref="transactionTemplate" ></property>
        </bean>  
    
    </beans>
    
  4. 测试异常操作数据库,数据库数据没有变化。

注解配置(aop)

  1. 导包

    • aop
    • aspect
    • aop联盟
    • weaving织入包
  2. 导入新的约束(tx)

    • beans: 最基本
    • context:读取properties配置
    • aop:配置aop
    • tx:配置事务通知
  3. 开启注解管理事务
    <tx:annotation-driven/>

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
    
        <!-- 指定spring读取db.properties配置 -->
        <context:property-placeholder location="classpath:db.properties"  />
        
        <!-- 事务核心管理器,封装了所有事务操作. 依赖于连接池 -->
        <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
            <property name="dataSource" ref="dataSource" ></property>
        </bean>
        <!-- 事务模板对象 -->
        <bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate" >
            <property name="transactionManager" ref="transactionManager" ></property>
        </bean>
        
        <!-- 开启使用注解管理aop事务 -->
        <tx:annotation-driven/>
        
        <!-- 1.将连接池 -->
        <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
            <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
            <property name="driverClass" value="${jdbc.driverClass}" ></property>
            <property name="user" value="${jdbc.user}" ></property>
            <property name="password" value="${jdbc.password}" ></property>
        </bean>
        
        
        
        <!-- 2.Dao-->
        <bean name="accountDao" class="cn.itcast.dao.AccountDaoImpl" >
            <property name="dataSource" ref="dataSource" ></property>
        </bean>
        <!-- 3.Service-->
        <bean name="accountService" class="cn.itcast.service.AccountServiceImpl" >
            <property name="ad" ref="accountDao" ></property>
            <property name="tt" ref="transactionTemplate" ></property>
        </bean>  
    
    </beans>
    
  4. 使用注解

    在类上和方法上都可以添加事务注解,方法上的注解可以覆盖类上的注解。

    @Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=true)
    public class AccountServiceImpl implements AccountService {
    
        private AccountDao ad ;
        private TransactionTemplate tt;
        
        @Override
        @Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)
        public void transfer(final Integer from,final Integer to,final Double money) {
            //减钱
            ad.decreaseMoney(from, money);
            int i = 1/0;
            //加钱
            ad.increaseMoney(to, money);
        }
    
        public void setAd(AccountDao ad) {
            this.ad = ad;
        }
    
        public void setTt(TransactionTemplate tt) {
            this.tt = tt;
        }
    }
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,099评论 18 139
  • 1.IOC与DI inverse of control 控制反转我们创建对象的方式反转了。以前对象的创建由开发人员...
    蕊er阅读 302评论 0 0
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,293评论 18 399
  • AOP注解开发光速入门 步骤一:引入相关的jar及配置文件 步骤二:编写目标类 步骤三:开启aop注解自动代理 常...
    日落perfe阅读 582评论 0 1
  • 一直以来,特别喜欢中国的传统文化,喜欢那种带有年代感的东西。一幢六角玲珑塔,勾勒不出历史前进的车辙;一户方...
    孤枭阅读 285评论 1 1