For investors
股价:
5.36 美元 %For investors
股价:
5.36 美元 %认真做教育 专心促就业
昆明达内培训的老师今天接上一期的知识点继续给大家讲异常抛出增强和环绕增强。
源码介绍:
1.User.java
package cn.zhang.entity;
public class User {
private Integer id; //用户ID
private String username; //用户名
private String password; //密码
private String email; //电子邮件
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(Integer id, String username, String password, String email) {
super();
this.id = id;
this.username = username;
this.password = password;
this.email = email;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
2.UserService.java
View Code
3.ErrorLog.java(异常抛出增强)
package cn.zhang.aop;
//异常抛出增强
import java.lang.reflect.Method;
import org.apache.log4j.Logger;
import org.springframework.aop.ThrowsAdvice;
public class ErrorLog implements ThrowsAdvice {
private static final Logger log = Logger.getLogger(ErrorLog.class);
public void afterThrowing(Method method, Object[] args, Object target,
RuntimeException e){
log.error(method.getName() + "方法发生异常:" + e);
}
}
4.AroundLog(环绕增强)
View Code
5.applicationContext.xml(Spring配置文件)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="#/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="#/schema/aop"
xmlns:p="#/schema/p"
xsi:schemaLocation="
#/schema/beans
#/schema/beans/spring-beans.xsd
#/schema/aop
#/schema/aop/spring-aop-4.1.xsd
">
<bean id="service" class="cn.zhang.service.UserService" />
<!--异常抛出增强-->
<!-- <bean id="error" class="cn.zhang.aop.ErrorLog"/> -->
<!--环绕增强-->
<bean id="error" class="cn.zhang.aop.AroundLog"/>
<aop:config>
<aop:pointcut expression="execution(public void delete())"
id="pointcut" />
<aop:advisor advice-ref="error" pointcut-ref="pointcut" />
</aop:config>
</beans>
6.MyTest.java
package cn.zhang.test;
//测试类
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.zhang.service.UserService;
public class MyTest {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml");
UserService service = (UserService) ctx.getBean("service");
try {
service.delete();
} catch (Exception e) {
System.out.println("错误了");
}
System.out.println("success!");
}
}
下一期昆明达内培训的老师还会继续给大家讲注解增强方式的前后置增强。