Spring--AOP(二)

第一节:AOP 简介
AOP 简介:百度百科;
面向切面编程(也叫面向方面编程):Aspect Oriented Programming(AOP),是软件开发中的一个热点,也是 Spring
框架中的一个重要内容。利用 AOP 可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度
降低,提高程序的可重用性,同时提高了开发的效率。
主要的功能是:日志记录,性能统计,安全控制,事务处理,异常处理等等。

第二节:Spring AOP实例
1,前置通知;
2,后置通知;
3,环绕通知;
4,返回通知;
5,异常通知;

 要引入命名空间和xsd :  xmlns:aop="http://www.springframework.org/schema/aop"    http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd"

<?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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
    
    <bean id="studentServiceAspect" class="com.java1234.advice.StudentServiceAspect"></bean>
    
    <bean id="studentService" class="com.java1234.service.impl.StudentServiceImpl"></bean>
    
    <aop:config>
    <!-- ref 是引用切面的bean, id只是定义名字相同而已  -->
        <aop:aspect id="studentServiceAspect" ref="studentServiceAspect">
            <aop:pointcut expression="execution(* com.java1234.service.*.*(..))" id="businessService"/>
            <aop:before method="doBefore" pointcut-ref="businessService"/>
            <aop:after method="doAfter" pointcut-ref="businessService"/> 
            <aop:around method="doAround" pointcut-ref="businessService"/>
            <aop:after-returning method="doAfterReturning" pointcut-ref="businessService"/>
            <aop:after-throwing method="doAfterThrowing" pointcut-ref="businessService" throwing="ex"/>  
        </aop:aspect> 
    </aop:config>
</beans>
View Code
public class StudentServiceAspect {

    public void doBefore(JoinPoint jp){
        System.out.println("类名:"+jp.getTarget().getClass().getName());
        System.out.println("方法名:"+jp.getSignature().getName());
        System.out.println("开始添加学生:"+jp.getArgs()[0]);
    }
    
    public void doAfter(JoinPoint jp){
        System.out.println("类名:"+jp.getTarget().getClass().getName());//StudentServiceImpl
        System.out.println("方法名:"+jp.getSignature().getName());//addStudent
        System.out.println("学生添加完成:"+jp.getArgs()[0]);//张三
    }
    
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable{
        System.out.println("添加学生前");
        Object retVal=pjp.proceed();
        System.out.println(retVal); //null
        System.out.println("添加学生后");
        return retVal;
    }
    
    public void doAfterReturning(JoinPoint jp){
        System.out.println("返回通知");
    }
    
    public void doAfterThrowing(JoinPoint jp,Throwable ex){
        System.out.println("异常通知");
        System.out.println("异常信息:"+ex.getMessage());
    }
}



public class StudentServiceImpl implements StudentService{

    @Override
    public void addStudent(String name) {
        // System.out.println("开始添加学生"+name);
        System.out.println("添加学生"+name);
        System.out.println(1/0);
        // System.out.println("完成学生"+name+"的添加");
    }

}


public class T {

    public static void main(String[] args) {
        ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
        StudentService studentService=(StudentService)ac.getBean("studentService");
        studentService.addStudent("张三");
        
    }
    

}
View Code

 

第四章 Spring对DAO的支持

第一节:Spring 对JDBC的支持
1,配置数据源 dbcp;
2,使用 JdbcTemplate;

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
        
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    
    <context:property-placeholder location="jdbc.properties"/>
    
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    
    
    <bean id="studentDao" class="com.java1234.dao.impl.StudentDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean> 
    
    <bean id="studentService" class="com.java1234.service.impl.StudentServiceImpl">
        <property name="studentDao" ref="studentDao"></property>
    </bean> 
    
</beans>
beans.xml
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_spring
jdbc.username=root
jdbc.password=123456
jdbc.properties
public class StudentDaoImpl implements StudentDao{

    private JdbcTemplate jdbcTemplate;
    
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public int addStudent(Student student) {
        String sql="insert into t_student values(null,?,?)";
        Object []params=new Object[]{student.getName(),student.getAge()};
        return jdbcTemplate.update(sql,params);
    }

    @Override
    public int updateStudent(Student student) {
        String sql="update t_student set name=?,age=? where id=?";
        Object []params=new Object[]{student.getName(),student.getAge(),student.getId()};
        return jdbcTemplate.update(sql,params);
    }

    @Override
    public int deleteStudent(int id) {
        String sql="delete from t_student where id=?";
        Object []params=new Object[]{id};
        return jdbcTemplate.update(sql,params);
    }

    @Override
    public List<Student> findStudents() {
        String sql="select * from t_student";
        final List<Student> studentList=new ArrayList<Student>();
        jdbcTemplate.query(sql, new RowCallbackHandler(){

            @Override
            public void processRow(ResultSet rs) throws SQLException {
                Student student=new Student();
                student.setId(rs.getInt("id"));
                student.setName(rs.getString("name"));
                student.setAge(rs.getInt("age"));
                studentList.add(student);
            }
            
        });
        return studentList;
    }

}

==========================================


public class StudentServiceImpl implements StudentService{

    private StudentDao studentDao;
    
    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }

    @Override
    public int addStudent(Student student) {
        return studentDao.addStudent(student);
    }

    @Override
    public int updateStudent(Student student) {
        return studentDao.updateStudent(student);
    }

    @Override
    public int deleteStudent(int id) {
        return studentDao.deleteStudent(id);
    }

    @Override
    public List<Student> findStudents() {
        return studentDao.findStudents();
    }

    

}
View Code

 3,JdbcDaoSupport 的使用;

StudentDaoImpl extends JdbcDaoSupport , dataSource 可以直接注入StudentDaoImpl, 比原来的间接一些。

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
        
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    
    <context:property-placeholder location="jdbc.properties"/>
    
 
    
    <bean id="studentDao" class="com.java1234.dao.impl.StudentDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean> 
    
    <bean id="studentService" class="com.java1234.service.impl.StudentServiceImpl">
        <property name="studentDao" ref="studentDao"></property>
    </bean> 
    
</beans>
View Code
public class StudentDaoImpl extends JdbcDaoSupport implements StudentDao{

    @Override
    public int addStudent(Student student) {
        String sql="insert into t_student values(null,?,?)";
        Object []params=new Object[]{student.getName(),student.getAge()};
        return this.getJdbcTemplate().update(sql,params);
    }

    @Override
    public int updateStudent(Student student) {
        String sql="update t_student set name=?,age=? where id=?";
        Object []params=new Object[]{student.getName(),student.getAge(),student.getId()};
        return this.getJdbcTemplate().update(sql,params);
    }

    @Override
    public int deleteStudent(int id) {
        String sql="delete from t_student where id=?";
        Object []params=new Object[]{id};
        return this.getJdbcTemplate().update(sql,params);
    }

    @Override
    public List<Student> findStudents() {
        String sql="select * from t_student";
        final List<Student> studentList=new ArrayList<Student>();
        this.getJdbcTemplate().query(sql, new RowCallbackHandler(){

            @Override
            public void processRow(ResultSet rs) throws SQLException {
                Student student=new Student();
                student.setId(rs.getInt("id"));
                student.setName(rs.getString("name"));
                student.setAge(rs.getInt("age"));
                studentList.add(student);
            }
            
        });
        return studentList;
    }

}
View Code

4,NamedParameterJdbcTemplate 的使用;支持命名参数变量;
org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate

 看源码,数据源要要使用构造方法传入。 以前jdbc传参是? ,现在是命名参数 :name

public class StudentDaoImpl implements StudentDao{

    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    
    public void setNamedParameterJdbcTemplate(
            NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
    }

    @Override
    public int addStudent(Student student) {
        String sql="insert into t_student values(null,:name,:age)";
        MapSqlParameterSource sps=new MapSqlParameterSource();
        sps.addValue("name", student.getName());
        sps.addValue("age", student.getAge());
        return namedParameterJdbcTemplate.update(sql,sps);
    }

    @Override
    public int updateStudent(Student student) {
        String sql="update t_student set name=:name,age=:age where id=:id";
        MapSqlParameterSource sps=new MapSqlParameterSource();
        sps.addValue("name", student.getName());
        sps.addValue("age", student.getAge());
        sps.addValue("id", student.getId());
        return namedParameterJdbcTemplate.update(sql,sps);
    }

    @Override
    public int deleteStudent(int id) {
        String sql="delete from t_student where id=:id";
        MapSqlParameterSource sps=new MapSqlParameterSource();
        sps.addValue("id", id);
        return namedParameterJdbcTemplate.update(sql,sps);
    }

    @Override
    public List<Student> findStudents() {
        String sql="select * from t_student";
        final List<Student> studentList=new ArrayList<Student>();
        namedParameterJdbcTemplate.query(sql, new RowCallbackHandler(){

            @Override
            public void processRow(ResultSet rs) throws SQLException {
                Student student=new Student();
                student.setId(rs.getInt("id"));
                student.setName(rs.getString("name"));
                student.setAge(rs.getInt("age"));
                studentList.add(student);
            }
            
        });
        return studentList;
    }

}
View Code
<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
        
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    
    <context:property-placeholder location="jdbc.properties"/>
    
    <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
        <!-- 看源码,要使用构造方法传入 -->
        <constructor-arg ref="dataSource"></constructor-arg>
    </bean>
    
    
    <bean id="studentDao" class="com.java1234.dao.impl.StudentDaoImpl">
        <property name="namedParameterJdbcTemplate" ref="namedParameterJdbcTemplate"></property>
    </bean> 
    
    <bean id="studentService" class="com.java1234.service.impl.StudentServiceImpl">
        <property name="studentDao" ref="studentDao"></property>
    </bean> 
    
</beans>
View Code

 

posted @ 2017-04-01 12:00  SKYisLimit  阅读(77)  评论(0)    收藏  举报