spring教程(下)

一、Spring 框架的 AOP

  1.Spring 中基于 AOP 的 @AspectJ   

package com.liandy.model;

import java.util.*;

import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Student {
    private String name;
    private int age;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    public void printThrowException(){
        System.out.println("Exception raised");
        throw new IllegalArgumentException();
    }
}
Student  
package com.liandy.model;


import org.aspectj.lang.annotation.*;

@Aspect
public class Logging {

    @Pointcut("execution(* com.liandy.model.*.*(..))")
    private void selectAll(){}
/**
* This is the method which I would like to execute
* before a selected method execution.
*/
    @Before("selectAll()")
public void beforeAdvice(){
System.out.println("Going to setup student profile.");
}
/**
* This is the method which I would like to execute
* after a selected method execution.
*/
    @After("selectAll()")
public void afterAdvice(){
System.out.println("Student profile has been setup.");
}
/**
* This is the method which I would like to execute
* when any method returns.
*/
    @AfterReturning(pointcut = "selectAll()", returning="retVal")
public void afterReturningAdvice(Object retVal){
System.out.println("Returning:" + retVal.toString() );
}
/**
* This is the method which I would like to execute
* if there is an exception raised.
*/
    @AfterThrowing(pointcut = "selectAll()", throwing = "ex")
public void AfterThrowingAdvice(IllegalArgumentException ex){
System.out.println("There has been an exception- " + ex.toString());
}
}
Logging
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<aop:aspectj-autoproxy/>
<!-- bean definitions go here -->
    <bean id="student" class="com.liandy.model.Student">
        <property name="name" value="jake"></property>
        <property name="age" value="12"></property>
    </bean>
    <bean id="logging" class="com.liandy.model.Logging"/>
</beans>
applicationContext.xml  
package com.liandy.main;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

import com.liandy.model.Cat;
import com.liandy.model.CustomEventPublisher;
import com.liandy.model.Foo;
import com.liandy.model.FooConfig;
import com.liandy.model.HelloWorld;
import com.liandy.model.Student;
import com.liandy.model.TestBean;
import com.liandy.model.TestConfiguration;
import com.liandy.service.UserService;

public class App {

    public static void main(String[] args) throws InterruptedException {                
        ApplicationContext context =
                new ClassPathXmlApplicationContext("applicationContext.xml");
                Student student = (Student) context.getBean("student");
                student.getName();
                student.getAge();
                student.printThrowException();
    }
}
App

 

二、JDBC 框架概述

   1.Spring JDBC的示例  

package com.liandy.model;

public class Customer {
    private int id;
    private String name;
    public Customer(String name) {
        super();
        this.name = name;
    }
    public Customer(int id, String name) {
        // TODO Auto-generated constructor stub
        this.id=id;
        this.name=name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void print()
    {
        System.out.print("id:"+this.id+"|name:"+this.name);
    }
}
Customer
package service;

import com.liandy.model.Customer;


public interface CustomerDAO {
    public void insert(Customer customer);
    public Customer findByCustomerId(int custId);
    public void insertByJdbcTemplate(Customer customer);
}
CustomerDAO
package service.imp;

import java.sql.*;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;



import com.liandy.model.Customer;

import service.CustomerDAO;

public class JdbcCustomerDAO implements CustomerDAO {

    private DataSource dataSource;
    private JdbcTemplate jdbcTemplate;
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    public void insertByJdbcTemplate(Customer customer){
        
        String sql = "INSERT INTO CUSTOMER " +
            "(id, NAME) VALUES (?, ?)";
                 
        jdbcTemplate = new JdbcTemplate(dataSource);
                
        jdbcTemplate.update(sql, new Object[] { customer.getId(),
            customer.getName()  
        });
                
    }
    public void insert(Customer customer){
        
        String sql = "INSERT INTO CUSTOMER " +
                "(id,name) VALUES (?, ?)";
        Connection conn = null;
        
        try {
            conn = dataSource.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setInt(1, customer.getId());
            ps.setString(2, customer.getName());
        
            ps.executeUpdate();
            ps.close();
            
        } catch (SQLException e) {
            throw new RuntimeException(e);
            
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {}
            }
        }
    }
    
    public Customer findByCustomerId(int custId){
        
        String sql = "SELECT * FROM CUSTOMER WHERE id = ?";
        
        Connection conn = null;
        
        try {
            conn = dataSource.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setInt(1, custId);
            Customer customer = null;
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                customer = new Customer(
                    rs.getInt("id"),
                    rs.getString("name")
                );
            }
            rs.close();
            ps.close();
            return customer;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if (conn != null) {
                try {
                conn.close();
                } catch (SQLException e) {}
            }
        }
    }

}
JdbcCustomerDAO
package com.liandy.main;


import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;





import service.CustomerDAO;

import com.liandy.model.Cat;
import com.liandy.model.CustomEventPublisher;
import com.liandy.model.Customer;
import com.liandy.model.Foo;
import com.liandy.model.FooConfig;
import com.liandy.model.HelloWorld;
import com.liandy.model.Student;
import com.liandy.model.TestBean;
import com.liandy.model.TestConfiguration;
import com.liandy.service.UserService;

public class App {

    public static void main(String[] args) throws InterruptedException {                
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "ApplicationContext.xml"); 
        CustomerDAO dao=(CustomerDAO) context.getBean("customerDAO");
        dao.insert(new Customer("aa"));
    }
}
App
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<aop:aspectj-autoproxy/>
<!-- bean definitions go here -->

    <import resource="springDatasource.xml" />
    <import resource="springCustomer.xml" />
</beans>
applicationContext.xml
<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="customerDAO" class="service.imp.JdbcCustomerDAO">
        <property name="dataSource" ref="dataSource" />
    </bean>

</beans>
springCustomer.xml
<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="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/mydb?useUnicode=true" />
        <property name="username" value="root" />
        <property name="password" value="" />
    </bean>

</beans>
springDataSource.xml

  2.事务管理

  • 原子性:事务应该当作一个单独单元的操作,这意味着整个序列操作要么是成功,要么是失败的。
  • 一致性:这表示数据库的引用完整性的一致性,表中唯一的主键等。
  • 隔离性:可能同时处理很多有相同的数据集的事务,每个事务应该与其他事务隔离,以防止数据损坏。
  • 持久性:一个事务一旦完成全部操作后,这个事务的结果必须是永久性的,不能因系统故障而从数据库中删
  除

 

posted @ 2018-07-19 20:48  连先森  阅读(159)  评论(0编辑  收藏  举报