"Java EE" ssh+spring security based on configuration aop+log4j

Source: Internet
Author: User

Spring Oauth2 In most cases is still not used, the main use is spring+springmvc+hibernate, sometimes with springsecurity, therefore, This article and the future article example will not contain the OAUTH2 configuration, need to put the former Applicationcontext-security.xml and Pom.xml plus on it, this article in the "ssh+spring Security building methods and example "the article is based on a number of adjustments, the main content is: Configure Spring AOP and use log4j to log.

1. Fine-tuning Some of the configuration files

The previous pom.xml, Spring-dispatcher-servlet.xml, Applicationcontext.xml and other configuration files are 1.1 points Plus, the code attached to this article has made some adjustments.

These files do not need to do any substantive changes, just do a fine-tuning, change the location of the content, not much to do the description.

2. Spring AOP

Aspect-oriented programming (Aspect oriented programming,AOP) breaks the program down into various aspects or calls attention points. With AOP, these features like transaction management can cut across multiple objects ' concerns. The main function of AOP is logging, transaction management, or data validation, and my example is for logging.

Spring The mechanism of AOP I was not very clear when I used ssh two years ago, so here are a few more key concepts besides usage:

    • aspect:aspect is a class , its methods are inserted into other class execution, this class can be configured through XML, or can be integrated with spring ASPECTJ through @aspect annotations, for example, I want to log the execution time for each DAO query method, Then the class that records the time of these facets is aspect;
    • < Span class= "emphasis" >join point: Connection point, which is where you want to insert the aspect code, in the example above, each DAO method to be recorded time is a joinpoint;
    • advice: Notice, a joinpoint can have multiple notifications, such as the method before the "before", the method before and after the "around", mainly before, after, after returning , after throwing, arount these 5 kinds;
    • < Span class= "emphasis" >pointcut: is an expression that matches a join point to determine if advice is to be triggered.

The following look at the specific configuration, the year is configured with XML, and now with the annotations provided by ASPECTJ, to be more convenient and intuitive.

First introduce the ASPECTJ package in Pom.xml (the Spring AOP package has been introduced as a dependency in the previous article):

<Properties>...<aspectj.version>1.8.2</aspectj.version></Properties><Dependencies>    <Dependency>        <groupId>Org.aspectj</groupId>        <Artifactid>Aspectjtools</Artifactid>        <version>${aspectj.version}</version>    </Dependency>    <Dependency>        <groupId>Org.aspectj</groupId>        <Artifactid>Aspectjrt</Artifactid>        <version>${aspectj.version}</version>    </Dependency></Dependencies>

Create the Aspect class below, create a package called aspect (my project is Org.zhangfc.demo4ssh.aspect), and create the aspect class:

@Component @aspect  Public class logaspect {}

@Aspect is an annotation provided by ASPECTJ, SPRING-AOP can parse the AOP configuration based on this annotation and annotations such as pointcut, which should be noted here @component annotations, which I did not match at first, It was later discovered that the spring container did not generate Logaspect bean at all, because @aspect this annotation is not spring's own, the IOC module does not recognize this annotation, so no management of this bean is created. Plus @component This annotation is meant to let spring manage it.

Add one of the simplest notifications below:

@Before ("Execution (* org.zhangfc.demo4ssh.service). *.*(..))" )publicvoid  Loggingserviceadvice () {    System.out.println ("executing Service ... ");

This notification means that any method that has arbitrary parameters and return values for any class under the service package and service sub-package will execute this method before execution (@Before).

Because to let spring to manage this bean, it is natural to configure the spring to automatically scan the package aspect, open Applicationcontext.xml, join:

<base-package= "Org.zhangfc.demo4ssh.aspect"/>

Since I am now configuring AOP primarily for logging, the configuration of AOP is placed in Hibernate's configuration file, open Infrastructure.xml, and at the end add a configuration that lets AOP auto proxy aspectj:

</>

Then run the program, and when the service method is executed, it will print out the executing service ... The statement. This is just a simple demo, the following to configure what we really need, the DAO access to the log, first to the program in the case of throwing exceptions, add the following method in the Logaspect class:

@AfterThrowing (value= "Within (ORG.ZHANGFC.DEMO4SSH). *) ", throwing =" ex ")publicvoid  loggingexceptions (joinpoint joinpoint, Exception ex) { C4/>system.err.println ("Exception thrown in Method ="            + joinpoint.tostring () + "" + Ex.getclass (). Getsimplenam E () + "=" + ex.getmessage ());}

@AfterThrowing is executed in the case of a matching method throwing an exception, this configuration is to indicate that in any class of any package under my project bundle, throwing an exception will let Loggingexceptions record, Now I'm writing a line in a DAO method that throws the exception code:

Integer.parseint ("ASD");

The following will be printed during the run:

inch string " ASD "

Finally, to configure DAO's access record, I want to create a slice before and after each DAO method executes, then I need to use @around notification, first to create a pointcut:

@Pointcut ("Execution (* Org.zhangfc.demo4ssh.repo). *.*(..))" )publicvoid  daopointcut () {}

This pointcut matches any method of any class under the repo package and the sub-package, and can then create around notifications based on this pointcut:

@Around ("Daopointcut ()") PublicObject Loggingaround (Proceedingjoinpoint joinpoint)throwsThrowable {LongStart =System.currenttimemillis (); System.out.println ("Method starts ..." + joinpoint.getsignature (). Getdeclaringtypename () + "_" + joinpoint.getsignature (). GetName () + "with" +arraytostring (Joinpoint.getargs ())); Object result=joinpoint.proceed (); Longdiff = System.currenttimemillis ()-start; System.out.println ("Method ends ..." + joinpoint.getsignature (). Getdeclaringtypename () + "_" + joinpoint.getsignature () . GetName () + "with" + diff + "MS"); returnresult;}PrivateString arraytostring (object[] traces) {StringBuilder trace=NewStringBuilder ();  for(Object s:traces) {trace.append (s==NULL? "": s.tostring () + "\ T"); }    if(trace.length () = = 0) {trace.append ("No parameter"); }    returntrace.tostring ();}

Run the output as follows:

Method Starts....org.zhangfc.demo4ssh.repo.userdao_findall with no Parametermethod ends .... Org.zhangfc.demo4ssh.repo.UserDao_findAll with 537ms

3. log4j

AOP is here, here, configure log4j, first import the log4j jar package:

<Dependency>    <groupId>Log4j</groupId>    <Artifactid>Log4j</Artifactid>    <version>1.2.17</version></Dependency>

log4j default configuration file needs to be placed under Classpath, and can not be sub-directory, configuration file more This is very inconvenient, if you feel that there is no problem in classpath, then put the configuration file can be directly run, I now want to change the directory of this configuration file, exactly, A spring class can help us with this, but configure it in Web. xml:

<Context-param>    <Param-name>Log4jconfiglocation</Param-name>    <Param-value>Classpath:/meta-inf/properties/log4j.properties</Param-value></Context-param><Context-param>    <Param-name>Log4jrefreshinterval</Param-name>    <Param-value>60000</Param-value></Context-param><Listener>    <Listener-class>Org.springframework.web.util.Log4jConfigListener</Listener-class></Listener>

This configuration is placed in front of Spring listener, specifying the configuration file location and re-reading the configuration file every 60 seconds, so that if the configuration is changed there is no need to restart the app. Configuration file configuration method I'm not going to go into the details, I'll put it in my configuration, and I'll output a copy of the configuration to the console and the file:

Log4j.rootlogger=info,console,Rolling_file#INFO, CONSOLE,Rolling_file#ERROR,Rolling_file####################Console Appender###################log4j. Appender. Console=org.apache.log4j.consoleappenderlog4j. Appender. Threshold=infolog4j. Appender. CONSOLE. Target=system.outlog4j. Appender. Console.layout=org.apache.log4j.patternlayoutlog4j. Appender. console.layout.conversionpattern=[%p]%d%c-%m%n#########################Rolling File########################log4j. Appender. Rolling_file=org.apache.log4j.rollingfileappenderlog4j. Appender. Rolling_file. Threshold=infolog4j. Appender. Rolling_file. File=${webapp.root}/web-inf/webapp.loglog4j. Appender. Rolling_file.Append=truelog4j. Appender. Rolling_file. Maxfilesize=5000kblog4j. Appender. Rolling_file. maxbackupindex=2log4j. Appender. Rolling_file.layout=org.apache.log4j.patternlayoutlog4j. Appender. Rolling_file.layout.conversionpattern=[%p]%d%c-%m%n

The format of the output demo is as follows:

[INFO] 2014-11-22 11:30:07,944 logaspect-method ends....org.zhangfc.demo4ssh.repo.userdao_findall with 385ms

The log files are placed under the web-inf of the project under configuration.

SOURCE download

Java EE ssh+spring security based on configuration aop+log4j

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.