Spring学习笔记(3)(二)

2014-11-24 09:24:17 · 作者: · 浏览: 1
Objectobj = null;

try {

//前置通知

System.out.println("执行权限检查...........");

obj = point.proceed();//放行,即执行目标对象上的方法

//后置通知

System.out.println("执行审计功能...........");

}catch (Throwable e) {

//异常通知

System.out.println("出现异常" + e.getMessage());

thrownew RuntimeException(e.getMessage());

}finally {

//最终通知

System.out.println("方法调用完了");

}

return obj;

}

}

配置文件:

2.3AOP通知详解—基于Annotation配置
1)用到的注解

@Aspect 用在类上,说明该类是一个切面Bean。

@Pointcut("execution(*com.maple.spring..*(..))")用在自定义方法上,定义一个切入点

@Before("personDAOMehtods()")前置通知

@AfterReturning("personDAOMehtods()")后置通知

@AfterThrowing(pointcut="personDAOMehtods()",throwing="e")@After("personDAOMehtods()")最终通知

@Around("personDAOMehtods()")环绕通知

@Aspect//说明该类是一个切面Bean

publicclassWriteLogAspectAnntation {

//配置一个名为personDAOMehtods()的切入点

@Pointcut("execution(*com.maple.spring..*(..))")

publicvoidpersonDAOMehtods(){ }

@Before("personDAOMehtods()")

publicvoid writeLogBefore() {

System.out.println(UserContext.getUser()+"准备调用方法");

}

@AfterReturning("personDAOMehtods()")

publicvoid writeLogAfter() {

System.out.println(UserContext.getUser()+"调用方法成功");

}

@AfterThrowing(pointcut="personDAOMehtods()", throwing="e")

publicvoidwrtetLogThrow(Exception e) {

System.out.println(UserContext.getUser()+"出现异常:" +e.getMessage() + new Date());

}

@After("personDAOMehtods()")

publicvoid wrtetLogFianl() {

System.out.println(UserContext.getUser()+"最终。。。" + new Date());

}

}

3. Spring中的数据库
3.1模版技术
把具有相同功能的代码模板抽取到一个工具类中。如把访问jdbc的模板代码抽到Template中,使用模板类,可以不用管有关连接管理,关闭等细节。只在我们的代码包括核心业务的代码把访问jdbc的模板代码抽到Template中,使用模板类,可以不用管有关连接管理,关闭等细节。只在我们的代码包括核心业务的代码。

3.2 Spring中的JdbcTemplete
Spring 提供了JdbcTemplate类,用于简化jdbc操作。只要写核心业务代码就可以了。

publicclass PersonImpl implements IPersonDAO {

//使用Sprig提供的jdbc操作模版

private JdbcTemplate template;

/**

* 提供setter方法,让spring注入值

* @param template

*/

publicvoid setTemplate(JdbcTemplatetemplate) {

this.template = template;

}

@Override

publicvoid save(final Person p) {

//调用自定的executeUpdate方法进行保存

Stringsql = "insert into persons(name, age) values('"+ p.getName() + "', " + p.getAge()+ ")";

template.execute(sql);

}

@Override

publicvoid remove(final Long id) {

Stringsql = "delete from persons where id=" + id;

template.execute(sql);

}

@Override

publicvoid update(final Long id, final Person p) {

Stringsql = "update persons set name='" + p.getName() + "', age=" + p.getAge() +" where id =" + id;

template.execute(sql);

}

}

配置文件:

3.3使用JdbcTemplete最好的方式
以上方式使用Spring提供的JdbcTemplete还需要手动注入。不是最