What is? AOP?AOP Use scenarios ?AOP Relevant concepts ?Spring AOP Components ? How to use Spring AOP? And so on. Please refer to the blog :Spring AOP Realization principle

The following focuses on how to write the event log function , Save the log to the database . 
Event logs are logic independent of the main business function , use AOP Implementation is the best , Because the field parameters in some database log tables need to be passed , So custom annotations are used , Pass these parameters in custom annotations .

1. Custom annotation Operation

package com.jykj.demo.filter;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; /**
* @Descrption This annotation describes the operation type of the method and the parameter meaning of the method
*/
@Target(value = ElementType.METHOD)
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
public @interface Operation {
/**
* @Description Describe the type of operation Is required ,1: Log in 2: The operation log
*/
int type(); /**
* @Description Describe the meaning of the operation For example, Declaration passed or failed
*/
String desc() default ""; /**
* @Description Describe the parameter meaning of the operation method The array length should be consistent with the parameter length , Otherwise, the parameters are inconsistent with the description
*/
String[] arguDesc() default {};
}

2. Section class EventLogAspect

package com.jykj.demo.filter;
import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired; import com.jykj.demo.service.SysEventService; // The event log section , Usually with @Operation Annotated service Methods will be logged
public class EventLogAspect {
@Autowired
SysEventService sysEventService; public void doAfterReturning(JoinPoint jp) {
System.out.println(
"log Ending method: " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName());
Method proxyMethod = ((MethodSignature) jp.getSignature()).getMethod();
Method soruceMethod;
try { soruceMethod = jp.getTarget().getClass().getMethod(proxyMethod.getName(), proxyMethod.getParameterTypes());
Operation oper = soruceMethod.getAnnotation(Operation.class); if (oper != null) {
System.out.println(oper.desc());
// Analytical parameters
sysEventService.insertEventLog(oper.type(),oper.desc()+"("+extractParam(jp.getArgs(),oper.arguDesc())+") success ");
} } catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
public void doAfterThrowing(JoinPoint jp, Throwable ex) {
Method proxyMethod = ((MethodSignature) jp.getSignature()).getMethod();
Method soruceMethod;
try {
soruceMethod = jp.getTarget().getClass().getMethod(proxyMethod.getName(), proxyMethod.getParameterTypes());
Operation oper = soruceMethod.getAnnotation(Operation.class);
if (oper != null) {
System.out.println(oper.desc());
sysEventService.insertEventLog(oper.type(),oper.desc()+
"("+extractParam(jp.getArgs(),oper.arguDesc())+" Something unusual happened :"+ex.getMessage());
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
}
private String extractParam(Object[] objParam, String[] arguDesc) {
StringBuilder sb = new StringBuilder();
int len = objParam.length<arguDesc.length?objParam.length:arguDesc.length;// Minimum value
for (int i = 0; i < len; i++) {
// Empty strings will not be parsed
if(arguDesc[i]!=null && !arguDesc[i].isEmpty()){
sb.append(arguDesc[i]+":"+objParam[i]+",");
}
}
String rs = sb.toString();
return rs.substring(0,rs.length()-1);
}
}

3. The breakthrough point Main business logic class FrmAppsService

package com.jykj.demo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.jykj.demo.dao.FrmAppsMapper;
import com.jykj.demo.entity.FrmApps;
import com.jykj.demo.filter.Operation;
import com.jykj.demo.mapper.AbstractService; @Service
public class FrmAppsService {
@Autowired
FrmAppsMapper mapper; @Operation(type=1,desc=" Update framework application ",arguDesc={""," Operation type "})
public int access(FrmApps app,String action){
return mapper.access(app,action);
}
}

4.Spring xml Yes AOP Configuration of

 <bean id="aspectEventLog" class="com.jykj.demo.filter.EventLogAspect" />
<!-- <aop:aspectj-autoproxy /> -->
<!-- To configure service All methods of all classes or interfaces under the package -->
<aop:config proxy-target-class="true">
<aop:aspect id="EventLogAspect" ref="aspectEventLog">
<aop:pointcut id="myService"
expression="execution(* com.jykj.demo.service.*.*(..)) " />
<aop:after-returning pointcut-ref="myService" method="doAfterReturning"/>
<aop:after-throwing pointcut-ref="myService" method="doAfterThrowing" throwing="ex"/>
</aop:aspect>
</aop:config>
<!-- controller -->
<context:component-scan base-package="com.jykj.demo.controller" />
<!-- service -->
<context:component-scan base-package="com.jykj.demo.service" />
<context:component-scan base-package="com.jykj.demo.filter" />

It should be noted that proxy-target-class=”true” , If you don't have this , If the target class implements the interface , Will take JDK Way of agency , Otherwise, it's CGLib Way of agency , If the startup project reports an error , The problem that the proxy class cannot be converted will be reported , At this time, just write down the configuration .

In this way, the function of writing log is realized , As long as you need to write a log service Class with custom annotations Operation Annotations can be

5. Output ( When editing a record )

log Ending method: com.jykj.demo.service.FrmAppsService.access
Update framework application
log Ending method: com.jykj.demo.service.SysEventService.insertEventLog

Plus Disable access to the page when not logged in Using interceptors  
SecurityInterceptor class

package com.jykj.demo.filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import com.jykj.demo.util.Helper; public class SecurityInterceptor implements HandlerInterceptor{ @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
HttpSession session = request.getSession();
if (session.getAttribute(Helper.SESSION_USER) == null) {
throw new AuthorizationException();
} else {
return true;
}
} @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub } @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub } }

Configuration of the corresponding interceptor spring-mvc.xml

<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/*"/>
<mvc:exclude-mapping path="/login"/>
<mvc:exclude-mapping path="/signIn"/>
<mvc:exclude-mapping path="/register"/>
<bean class="com.jykj.demo.filter.SecurityInterceptor">
</bean>
</mvc:interceptor>
</mvc:interceptors>
<!-- bean Deal with no login redirection to login interface -->
<bean id="handlerExceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.jykj.demo.filter.AuthorizationException">redirect:login</prop>
</props>
</property>
</bean>

Exception class AuthorizationException

package com.jykj.demo.filter;
public class AuthorizationException extends Exception{
private static final long serialVersionUID = 1L;
}

Refer to the post :Spring Aop Log interception application  
Refer to the post : Configuration based Spring AOP 
Refer to the post :Spring AOP Detailed explanation

 
 

Spring AOP Write event log function to achieve more related articles

  1. Spring Boot 2.X( 8、 ... and ):Spring AOP Implement simple log facets

    AOP 1. What is? AOP ? AOP The full name is Aspect Oriented Programming, Face to face programming , It is a way to achieve the unified maintenance of crosscutting behavior beyond the core business logic by precompiling and runtime dynamic proxy ...

  2. utilize Spring AOP Custom annotation solves log and signature verification

    Reprint :http://www.cnblogs.com/shipengzhi/articles/2716004.html One . Problems to be solved part API There are signature parameters (signature),Passport First ...

  3. spring AOP Custom annotation Realize log management

    Today we continue to achieve AOP, I think it's the most flexible here , Scalable way , Take log management for example , use Spring AOP User defined annotation form to realize log management . I don't say much nonsense , Just start !!! I'll say it again about configuration . stay appli ...

  4. ( turn ) utilize Spring AOP Custom annotation solves log and signature verification

    One . Problems to be solved part API There are signature parameters (signature),Passport First, check the signature , The implementation method will only be executed if the verification is passed . The first implementation (Origin): Write verification code in the interface that needs signature verification , for example : ...

  5. spring aop Logging through annotations

    First, a few concepts : Connection point (Joinpoint). Tangent point (Pointcut). enhance (Advice). section (Aspect) In addition, we should also use annotations . demand : Define... By annotations LogEnable. Then the program runs to identify the definition ...

  6. springboot—spring aop Realize the storage of system operation log to database

    original text :https://www.jianshu.com/p/d0bbdf1974bd Adopt scheme : Use spring Of aop Technology cuts to custom annotations , Parameter analysis for different annotation marks , Log The drawback is to aim at ...

  7. Spring AOP Section implementation operation log

    Create an interface annotation log class package com.fh.service.logAop; /** * Created by caozengling on 2018/7/21. */ import java.l ...

  8. spring AOP Knowledge point summary and log output

    AOP It's based on OCP On the basis of not changing the core business code of the original system, some extended functions are added dynamically . It is usually applied to the processing of logs , Transaction processing , Authority handling , Cache processing and so on First , Use AOP The dependencies that need to be added are :spring-conte ...

  9. use Spring AOP+Log4j Log the project

    Reprint please indicate the source :http://www.cnblogs.com/Joanna-Yan/p/6567672.html Project logging is project development . What's essential to operations , With it, we can control the system as a whole , Any problems ...

Random recommendation

  1. unity Reading text and writing text

    void writeData(string str,string file)    {        string parth = Application.dataPath;        Strea ...

  2. kendoui-grid piece

    kendo It's really a good thing , It allows us to focus on back-end development , There's no need to put a lot of effort into the presentation of the effect , The only drawback , It's a charge , But I haven't found out why I have to pay for it , because free I've met my needs . kendoUI For asp.m ...

  3. Why? MVC It's not a design pattern ( turn )

    MVC(Model-View-Controller) It's a common solution when dealing with interface applications , It forms the presentation layer . MVC By separating models . View . The role of the controller in the application , Decouple interface and business logic .Model( yes OO ...

  4. css Initialize label properties -- Source code

    body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, form, fieldset, input, p, blockquote ...

  5. JAVA_ Interface _ The default method &amp; Static methods

    1. Summary ( Be careful ): 1. Member variables cannot be defined in an interface , But you can define constants , Its value cannot be changed , By default public static final modification 2. Interface , There is no way to construct , Cannot create object 3. Interface , There are no static code blocks ...

  6. docker( 7、 ... and ) Use dockerfile-maven-plugin Plug in build docker Mirror image

    stay dockerfile-maven-plugin Before the plug-in , One more maven The plug-in is docker-maven-plugin, Created by the same author , The author clearly recommends the use of dockerfile-maven- ...

  7. Java Two dimensional code generation and decoding

      be based on google zxing Of Java Two dimensional code generation and decoding   One . add to Maven rely on ( When decoding, you need to upload a QR code image , So you need to rely on the file upload package ) <!-- google QR code tools --> &l ...

  8. Xshell add to ssh Tunnel SOCKS agent

    Xshell It's a powerful Terminal Simulator , Support SSH,SFTP.TELNET.RLOGIN and SERIAL Download address :http://www.netsarang.com/products/xsh_overv ...

  9. Salesforce Data security protection measures of

    adopt Salesforce, We can configure or develop powerful network applications . meanwhile , Whether as administrator or developer , We all have to face the problem of data security . Common data security risks include : SQL Inject Cross-site scripting attacks Cross-site request forgery Click on ...

  10. Station SEO standard

    One : The originality of the article 1. Change the title of the article , Choose as new as possible , Titles that fit the user's search habits . 2. repair Change the first paragraph or do it yourself to add the first text message . 3. Pictures in the article ALT Property modification and addition . 4. Without affecting reading , ...