這篇文章旨在記錄關于SpringMVC過程中會用到的監聽器
1.Servlet監聽
用來監聽Servlet的生命周期。
主要類:ServletContextListener(監聽網站啟動過程),
HttpSessionListener(監聽客戶端會話過程), HttpSessionAttributeListener
實現:
創建類實現以上的接口比如:
public class TestListener implements ServletContextListener,
HttpSessionListener, HttpSessionAttributeListener {
.....
}
web.xml配置:
<listener>
<listener-class>com.test.TestListener</listener-class>
</listener>
2.Bean 初始化監聽
可以監聽Spring創建Bean的實例的初始化前后
主要類:
BeanPostProcessor
實現:
public class TestProcess implements BeanPostProcessor,Ordered {
public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
System.out.println("postProcessBeforeInitialization");
return o;
}
public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
System.out.println("postProcessAfterInitialization");
return o;
}
public int getOrder() {
return 1;
}
}
Order主要在于多個同等類時執行的順序,return返回的是對象,這里可以偷天換日。
SpringContext.xml:
<bean id="testpost" class="....TestProcess"></bean>
3.類的初始化和銷毀的監聽。
此監聽旨在監聽bean的自身初始化和銷毀過程,初始化的執行方法在第2個監聽之后
實現:
第一種1.SpringContext.xml
<bean id="helloWorld" class="com.tutorialspoint.HelloWorld"
init-method="init" destroy-method="destroy">
<property name="message" value="Hello World!"/>
</bean>
通過init-method和destroy-method設置。
第二種2.在bean中
@PostConstruct
public void init(){
System.out.println("Bean is going through init.");
}
@PreDestroy
public void destroy(){
System.out.println("Bean will destroy now.");
}
4.AOP。
面向切面編程
第一種方式:
SpringContext.xml:
<aop:config>
<aop:aspect id="myaspect" ref="peoAsp">
<aop:pointcut id="mypointcut" expression="execution(* jis.*.*(..))"/>
<aop:before method="beforeAdvice" pointcut-ref="mypointcut"/>
<aop:after-throwing method="AfterThrowingAdvice" pointcut-ref="mypointcut" throwing="ex"/>
<aop:after-returning method="afterReturningAdvice" pointcut-ref="mypointcut" returning="retVal"/>
</aop:aspect>
</aop:config>
第二種方式:
Bean中:
@Aspect
public class PeoAsp {
public PeoAsp(){}
@Pointcut("execution(* com.jis.People.aspTest(..))")
public 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.
*/
public void AfterThrowingAdvice(Exception ex){
System.out.println("There has been an exception: " + ex.toString());
}
}
并在SpringContext中配置:
<aop:aspectj-autoproxy/>
<bean class="com.jis.PeoAsp" id="peoAsp"></bean>