Spring Basics

Posted by talper on Mon, 07 Feb 2022 14:20:16 +0100

Important Spring modules

  1. Spring Core: the core module, which mainly provides IOC dependency injection
  2. Spring AOP: aspect oriented programming implementation
  3. Spring JDBC: connecting to database
  4. Spring Web: creating web applications
  5. Spring Test: test function of Junit and TestNG
  6. Spring WebSocket: it is easy to implement even chat components

@RestController and @ Controller

  1. The former: put it on a class, and all interfaces representing this class return JSON type data.
  2. The latter: return a page. If you want an interface to return JSON data, you need to add @ ResponseBody to the interface

Spring IOC and AOP

IOC, control inversion, refers to the control of manually creating objects in the program, which is managed by the spring framework. Spring is implemented as an IOC container, which is a map that stores various objects.
The specific implementation is dependency injection: the bottom class is passed to the upper class as a parameter to realize the control of the upper class over the bottom class. Some are passed through construction methods, as well as Set and interface.

Control inversion container: dependency injection is to inject the underlying classes that the upper class depends on. The initialization of these underlying classes is done by the container.
https://www.zhihu.com/question/23277575/answer/169698662

AOP, aspect oriented programming, encapsulates business independent logic and reduces system code duplication.
Based on dynamic proxy, if the proxy object implements an interface, JDK proxy of JDK is used. Otherwise, Cglib is used to generate a subclass of the proxied object

//JDKproxy
package com.example.demo;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKProxyDemo {
    static interface Inter{
        void oneMethod();
    }
    //Proxy class
    static class interImpl implements  Inter {

        @Override
        public void oneMethod() {
            System.out.println("Method execution of the proxy class");
        }

    }
    //Generate the processing class of the proxy class
    static class JdkProxy implements InvocationHandler {
        //Proxied class object
        private Object object;
        //Bind the proxied object to the processing class
        public Object bind(Object o) {
            this.object = o;
            return Proxy.newProxyInstance(object.getClass().getClassLoader(),
                    object.getClass().getInterfaces(),this);
        }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("Proxy class enhancements to methods");
            Object invoke = method.invoke(object, args);
            return invoke;
        }
    }

    public static void main(String[] args) {
        //Generate a proxy class
        JdkProxy jdkProxy = new JdkProxy();
        Inter inter = (Inter) jdkProxy.bind(new interImpl());
        //Dynamically generate proxy class objects
        inter.oneMethod();
    }
}
//Cglilb
package com.example.demo;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibDemo {
    static class SayHello {
        public void sayHello() {
            System.out.println("say hello");
        }
    }
    static class CglibDemoE implements MethodInterceptor {

        public Object getProxy(Class cls) {
            //cglib enhanced class object
            Enhancer enhancer = new Enhancer();
            //Set enhancement type
            enhancer.setSuperclass(cls);
            //Defines the proxy logical object as the current object
            enhancer.setCallback(this);
            return enhancer.create();
        }

        @Override
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            System.out.println("Enhanced");
            Object o1 = methodProxy.invokeSuper(o, objects);
            return o1;
        }
    }

    public static void main(String[] args) {
        CglibDemoE cglibDemoE = new CglibDemoE();
        SayHello proxy = (SayHello) cglibDemoE.getProxy(SayHello.class);
        proxy.sayHello();
    }
}

JDK dynamic proxy uses reflection technology, and the proxy class should implement method interface.
CGLIB dynamic proxy uses bytecode enhancement technology, and the proxy class does not need to implement method interface

Spring Bean

  1. Scope of Spring Bean
    Singleton: unique bean instance
    prototype: each request creates a new bean
    Request: one bean during a request
    Session: a bean during a session

  2. Do you understand the thread safety of singleton bean s in Spring?
    Singleton bean is a bean used by all threads, which has the problem of multi-threaded operation safety. However, spring is a singleton bean by default, because most beans are stateless, that is, they are only used by the controller, dao and service layers, and only operate methods.
    Stateless storage means no data. And stateless means that there are only methods, and the methods correspond to the virtual machine stack of the jvm.

    ThreadLocal can be used to encapsulate.

  3. @What is the difference between Component and @ Bean?
    The objects of action are different: the former functions and classes, while the latter functions and methods.
    @Component s are usually automatically detected and assembled into the Spring container through classpath scanning (we can use @ ComponentScan annotation to define the path to be scanned, find out the classes that need to be assembled, and automatically assemble them into the Spring bean container)@ Bean annotation is usually defined in the method marked with this annotation to generate this bean,@Bean tells Spring that this is an example of a class and returns it to me when I need to use it.

  4. What are the annotations for bean s that declare a class as Spring?
    @Component: a general annotation that can label any class as a Spring component. If a Bean does not know which layer it belongs to, it can be annotated with @ Component annotation.

    @Repository: the corresponding persistence layer, namely Dao layer, is mainly used for database related operations

    @Service: corresponding to the service layer, which mainly involves some complex logic, and the Dao layer is required.

    @Controller: corresponding to the Spring MVC control layer, the main user accepts the user request and calls the Service layer to return data to the front-end page

How Spring MVC works

  1. The client sends a request to the dispatcherservlet,
  2. The front-end Controller calls HanlerMapping according to the request and parses the handler corresponding to the request, that is, the corresponding Controller.
  3. After that, the HandlerAdapter adapter executes the specific process.
  4. After processing, a modelAndView object is returned. Model is data and View is a logical page.
  5. The view parser finds the real page view through view
  6. The front-end controller renders the data to the view, fills the data to the request, and responds to the data.

spring transaction

Declarative transactions, based on xml or annotations

  1. Transaction isolation level?
    Transaction definition defines five
    The default isolation level is consistent with the database isolation level, myslq is repeatable read, and oracle is read committed

    The rest are read uncommitted and read committed, which can be read repeatedly and serialized

  2. Transaction propagation behavior?
    Support current transaction:
    If there is a current transaction, add the current transaction; if there is no current transaction, create a new one
    Currently, there are transactions. If there is no transaction, it is no longer a transaction.
    There is currently a transaction, join, or throw an exception

    The current transaction is not supported
    Create a new transaction and suspend the current transaction if there is one
    Run as non transaction, suspend current
    Run as a non transaction, throw an exception if there is one currently

  3. @Do you understand the Transactional(rollbackFor = Exception.class) annotation?
    If it is not added, the data will only be rolled back when runtime exceptions are thrown. If it is added, the Exception will be rolled back

Topics: Java Spring Back-end