Implementing AOP with Java Dynamic Proxy


At present, AOP (aspect oriented programming) is highly praised by the whole development community, and a large number of excellent frameworks supporting AOP have emerged, — spring, JAC, JBoss, AOP, etc. AOP seems to have become a trend for a while. Java beginners can’t help but sigh that they haven’t learned OOP yet and come to AOP again. This article is not to elaborate what AOP is and why AOP should be carried out in theory. To learn AOP in detail, you can go to its hometown Go and have a look. Here is just a simple example to show beginners how to do AOP

For simplicity, the example does not use any third-party AOP framework, but uses the dynamic proxy function of the Java language itself to implement AOP

Let’s go back to AOP itself. AOP is mainly used in logging, performance statistics, security control, transaction processing and so on. Its main purpose is to clearly divide the logging, performance statistics, security control and other codes from the business logic code. We can regard these behaviors as the problems to be solved by the system one by one, which is the so-called problem-oriented programming. By separating these behaviors, we hope that they can be configured independently into the business method, and changing these behaviors does not need to affect the business method code.

Assuming that the system completes the business logic functions by a series of business objects, the system requires logging every time the business logic is processed. Here we omit the specific business logic code.

  public interface BusinessInterface {
  public void processBusiness();

  public class BusinessObject implements BusinessInterface {
  private Logger logger = Logger.getLogger(this.getClass().getName());
  public void processBusiness(){
  try {“start to processing…”);
   //business logic here.
   System.out.println(“here is business logic”);“end processing…”);
  } catch (Exception e){“exception happends…”);
   //exception handling

Here, the code dealing with business logic and logging code are mixed together, which will bring some difficulties to future maintenance and cause a lot of code duplication. The same log code will appear in every business object in the system.

Recommended Today

Perl implementation detects whether the services in the server share scripts normally

The program calls the remote service. In order to ensure availability, it is best to conduct health detection before use to exclude abnormal services.   Copy codeThe code is as follows: #!/usr/bin/perl   # use strict; use IO::Socket; my @servers; $servers[0]=[‘’,2222]; $servers[1]=[‘’,22]; $servers[2]=[‘’,80]; my $i=0; my $interval=3; my $count=int(60/$interval); while($i < $count){ foreach (@servers){ if(fetch_server_status(@$_)){ […]