The core idea of Spring is summed up very well!

Author: Java program yuanhuanhuan
https://blog.csdn.net/Lubanjava/article/details/100084602

Dependency injection is an embodiment of face-to-face interface programming and the core idea of Spring. In fact, dependency injection is not an advanced technology, but it's a little mysterious to be packaged by Spring.

class Main {
    interface Language {
        void print(String s);
    }

    static class Java implements Language{
        @Override
        public void print(String x) {
            System.out.println("System.out.print(\""+ x +"\")");
        }
    }

    static class Coder {
        private Language lang = new Java();

        public void helloWorld() {
            lang.print("hello world");
        }
    }

    public static void main(String[] args) {
        Coder coder = new Coder();
        coder.helloWorld();
    }
}

As shown in the code listing above, Coder uses the Java Language to print helloworld strings. Here, it not only depends on the Language interface, but also on Java classes, which makes it coupled with Java classes. It's easy to eliminate this dependency or decoupling.

interface Language {
  void print(String s);
}

static class Java implements Language{
  @Override
  public void print(String x) {
    System.out.println("System.out.print(\\""\+ x +"\\")");
  }
}

static class Coder {
  private Language lang;

  public void setLang(Language lang) {
    this.lang = lang;
  }

  public void helloWorld() {
    lang.print("hello world");
  }
}

public static void main(String\[\] args) {
  Coder coder = new Coder();
  Language java = new Java();
  coder.setLang(java);
  coder.helloWorld();
}

We have added the method of setting the specific Language to the Coder class, so that the Coder class only depends on the Language interface and does not depend on the specific Language implementation. In other words, the Coder class is decoupled from the specific Language. At this time, we can easily use other languages instead of Java, such as C.

static class CSharp implements Language{
    @Override
    public void print(String x) {
        System.out.println("Console.Write(\\""\+ x +"\\")");
    }
}

public static void main(String\[\] args) {
    Coder coder = new Coder();
    Language csharp = new CSharp();
    coder.setLang(csharp);
    coder.helloWorld();
}

WeChat official account: Java technology stack, back in the background: spring, can get the latest Spring tutorial I have compiled N, all dry cargo.

This technique of setting the specific object on which an object depends is dependency injection, which is quite surprising. One of the most common coding techniques has such a high name.

For the Coder class, determining which language to use is originally determined by the compiler period. After using dependency injection, which language to use will be delayed to the runtime.

The core idea of Spring framework is based on this, but its implementation goes further, and it makes the process of creating the dependency of each object dynamic and universal. In our code listing, the main method of creating objects and setting dependencies is only applicable to the current situation, while Spring's IOC container can be applicable to any situation

Generally, Spring's dependency is represented by XML, and IOC container parses XML to complete object creation and dependency injection.

We use the Spring framework to implement the previous code:

interface Language {
    void print(String s);
}
class Java implements Language{
    @Override
    public void print(String x) {
        System.out.println("System.out.print(\""+ x +"\")");
    }
}
class CSharp implements Language{
    @Override
    public void print(String x) {
        System.out.println("Console.Write(\""+ x +"\")");
    }
}
class Coder {
    private Language lang;

    public void setLang(Language lang) {
        this.lang = lang;
    }

    public Language getLang() {
        return lang;
    }

    public void helloWorld() {
        lang.print("hello world");
    }
}

Dependencies will be implemented by XML configuration

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="java" class="Java">
    </bean>

    <bean id="csharp" class="CSharp">
    </bean>

    <bean id="coder" class="Coder">
        <property name="lang" ref="csharp"></property>
    </bean>
</beans>

The code that creates the Coder object changes to

public static void main(String[] args) {
    ApplicationContext context = new FileSystemXmlApplicationContext("applicationContext.xml");
    Coder coder = (Coder) context.getBean("coder");
    coder.helloWorld();
}

Specific object creation and dependency setting will be completed by IOC according to XML configuration. Spring makes dependency injection mechanism automatic, but the essence of dependency injection has not changed. The latest Spring series tutorials in 2019 are all here , let's take a look at this recommendation.

Face-to-face programming can dynamically enhance the function without changing the original code, such as doing some things before or after a method execution, such as logging, calculating the running time and so on.

Aspectj is perfectly integrated in Spring, so it is very convenient for aspect oriented programming.

Spring Aspectj has several annotations for common aspect oriented programming functions

@Aspect
public class Logger {
    @Before("execution(* controller.Default.*(..))")
    public void before(JoinPoint join){}

    @After("execution(* controller.Default.*(..))")
    public void after(){}

    @AfterReturning("execution(* controller.Default.*(..))")
    public void afterReturning() {}

    @AfterThrowing("execution(* controller.Default.*(..))")
    public void afterThrowing(){}

    @Around("execution(* controller.Default.*(..))")
    public void around(ProceedingJoinPoint jp) {}
}

As shown in the above code, this class controller.Default Class.

@Before note

@Before annotation decorated methods will be executed before the enhanced methods are executed

@After comment

@After annotation decorated methods will be executed after the enhanced methods are executed

@AfterReturning note

@The method modified by the AfterReturning annotation will be executed After the enhanced method is executed, provided that the modified method is successfully executed. If an exception is thrown midway through the method, the method modified by the AfterReturning annotation will not be executed, and the method modified by the After annotation will be executed anyway.

@AfterThrowing annotation

@The method decorated by the AfterThrowing annotation will be executed in the case of an exception thrown by the enhanced method execution error.

@Around annotation

@Around annotation is a combination of @ Before annotation and @ After annotation. It can be enhanced Before and After the enhanced method

@Around("execution(* controller.Default.*(..))")
public void around(ProceedingJoinPoint jp) {
    try {
        System.out.println("before");
        jp.proceed();
        System.out.println("after");
    } catch (Throwable e) {
        System.out.println(e.getMessage());
    }
}

With this annotation, the enhanced method needs to be called manually

jp.proceed();

If you do not write this sentence in enhanced code, the enhanced method will not run.

In addition, there is an important annotation @ Pointcut

@Pointcut annotation

This annotation can be used to refine the pointcut

@Aspect
public class Logger {
    @Pointcut( value = "execution(* controller.Default.*(..))")
    public void pointcut() {}

    @Before("pointcut()")
    public void before(JoinPoint join){}

    @After("pointcut()")
    public void after(){}

    @AfterReturning("pointcut()")
    public void afterReturning() {}

    @AfterThrowing("pointcut()")
    public void afterThrowing(){}

    @Around("pointcut()")
    public void around(ProceedingJoinPoint jp) {}
}

@Before, @ After and other annotations can apply the pointcut of this annotation declaration to reduce code duplication.

Recommend to my blog to read more:

1.Java JVM, collection, multithreading, new features series

2.Spring MVC, Spring Boot, Spring Cloud series tutorials

3.Maven, Git, Eclipse, Intellij IDEA series tools tutorial

4.Latest interview questions of Java, backend, architecture, Alibaba and other large factories

Feel good, don't forget to like + forward!

Tags: Java Spring xml Programming

Posted on Thu, 18 Jun 2020 03:36:10 -0400 by Stille