Java must-see Spring knowledge summary! There's nothing more complete than that and I lose!

Wonderful recommendation in the past   


 

[1] Summary of Java Web technology experience

[2] 15 top Java multi-threading interview questions and answers, come and see

[3] Ten Java interview questions that interviewers like to ask

[4] Speak JAVA from scratch, giving you a clear learning path! Learn what to learn! !

[5] Welfare: 100G Java full set of learning videos are sent for free

 

The Spring framework was created due to the complexity of software development. Spring uses basic JavaBeans to do things that were previously only possible with EJBs. However, Spring's uses are not limited to server-side development. From the standpoint of simplicity, testability, and loose coupling, most Java applications can benefit from Spring.

 

Spring advantages:


 

 

Low intrusive design, extremely low code pollution;

Independent of various application servers, applications based on the Spring framework can truly realize the promise of Write Once and Run Anywhere;

Spring's IoC container reduces the complexity of business object replacement and improves decoupling between components

Spring's AOP support allows centralized management of common tasks such as security, transactions, logging, etc., thus providing better reuse;

Spring's ORM and DAO provide good integration with third-party persistence frameworks and simplify underlying database access;

The high degree of openness of spring does not force the application to completely depend on Spring. Developers can freely choose part or all of the Spring framework.

 

 

The composition diagram of the Spring framework:


 

Spring's core mechanism


 

 

Manage beans


 

The program mainly accesses the beans in the container through the Spring container. ApplicationContext is the most commonly used interface of the Spring container. This interface has the following two implementation classes:

 

ClassPathXmlApplicationContext: Search the configuration file from the class loading path, and create a Spring container according to the configuration file;

 

FileSystemXmlApplicationContext: Search the configuration file from the relative path or absolute path of the file system, and create a Spring container according to the configuration file

 

publicclassBeanTest{publicstaticvoidmain(String args) throws Exception{ ApplicationContext ctx =newClassPathXmlApplicationContext("beans.xml"); Person p = ctx.getBean("person", Person.class); p.say; } }

Eclipse uses Spring


 

In IDE tools such as Eclipse, users can build their own User Library, and then put all the Spring Jar packages in it. Of course, they can also directly put the Jar packages in the /WEB-INF/lib directory of the project, but if the User Library is used , when the project is released, the Jar file referenced by the user library needs to be released together with the application, that is, the Jar used by the User Library is copied to the /WEB-INF/lib directory, this is because for a web application, Eclipse deploys the web The Jar file of the user library will not be copied to /WEB-INF/lib during application, and it needs to be copied manually.

 

dependency injection


 

 

There are two core functions of the Spring Framework:

 

As a super factory, the Spring container is responsible for creating and managing all Java objects, which are called beans;

 

The Spring container manages the dependencies between beans in the container, and Spring uses a method called "dependency injection" to manage the dependencies between beans.

 

Using dependency injection, you can not only inject common property values ​​for beans, but also inject references to other beans. Dependency injection is an excellent way of decoupling, which allows beans to be organized together in configuration files instead of hard-coded coupling.

 

Understanding Dependency Injection


 

 

Rod Johnson was the first person to attach great importance to the use of configuration files to manage the cooperative relationship of Java instances, and he gave this method a name: Inverse of Control (IoC). Later Martine Fowler gave this method another name: Dependency Injection, so whether it is Dependency Injection or Inversion of Control, its meaning is exactly the same. When a Java object (the caller) needs to call a method of another Java object (the dependent object), there are usually two approaches in traditional mode:

 

Original practice: The caller actively creates the dependent object, and then calls the method of the dependent object;

 

Simple factory pattern: The caller first finds the factory of the dependent object, then actively obtains the dependent object through the factory, and finally calls the method of the dependent object.

 

Pay attention to the word active above, which will inevitably lead to hard-coded coupling between the caller and the implementation class of the dependent object, which is very unfavorable for the maintenance of project upgrades. After using the Spring framework, the caller does not need to actively obtain the depended object. The caller only needs to passively accept the Spring container to assign values ​​to the caller's member variables. It can be seen that after using Spring, the caller obtains the depended object by the original method. Active acquisition becomes passive acceptance - so Rod Johnson calls it Inversion of Control.

 

In addition, from the perspective of the Spring container, the Spring container is responsible for assigning the dependent object to the caller's member variables - equivalent to injecting its dependent instances for the caller, so Martine Fowler calls it dependency injection.

 

setpoint injection


 

 

Setter injection means that the IoC container injects the dependent object through the setter method of the member variable. This injection method is simple and intuitive, so it is widely used in Spring's dependency injection.

 

Construct injection


 

 

The use of constructors to set dependencies is called construction injection. In layman's terms, it is to drive Spring to execute the constructor with specified parameters in reflection at the bottom layer. When the constructor with parameters is executed, the constructor parameters can be used to initialize the member variables - this is the essence of construction injection.

 

Comparison of two injection methods:


 

 

Setpoint injection has the following advantages:


 

 

It is more similar to the traditional JavaBean writing, and it is easier for program developers to understand and accept. Setting dependencies through setter methods is more intuitive and natural;

 

For complex dependencies, if constructor injection is used, the constructor will be too bloated and difficult to read. When Spring creates a Bean instance, it needs to instantiate all instances of its dependencies at the same time, resulting in performance degradation. Using set-value injection can avoid these problems.

 

Especially in the case where some member variables are optional, the multi-parameter constructor is more cumbersome.

 

The advantages of construct injection are as follows:


 

 

Constructive injection can determine the injection order of dependencies in the constructor, giving priority to the priority injection of dependencies;

 

Construct injection is more useful for beans whose dependencies do not need to change. Because there is no setter method, all dependencies are set in the constructor, and there is no need to worry about the subsequent code destroying the dependencies;

 

Dependencies can only be set in the constructor, and only the creator of the component can change the dependencies of the component. For the caller of the component, the dependencies inside the component are completely transparent, which is more in line with the principle of high cohesion.

 

Notes recommends an injection strategy in which the setting injection is the main method and the construction injection is the supplementary injection. For injections whose dependencies do not need to be changed, use construction injection as much as possible; for injections of other dependencies, consider setting injection.

 

Beans in a Spring container

 

For developers, developers use the Spring framework mainly to do two things: ① develop beans; ② configure beans. For the Spring framework, all it has to do is to create a Bean instance according to the configuration file, and call the method of the Bean instance to complete "dependency injection" - this is the essence of the so-called IoC.

 

Scope of beans in the container


 

 

When a Bean instance is created through the Spring container, not only the instantiation of the Bean instance can be completed, but also a specific scope can be specified for the Bean. Spring supports the following five scopes:

 

singleton: Singleton mode, in the entire Spring IoC container, a singleton-scoped bean will generate only one instance;

 

prototype: A new Bean instance will be generated every time a Bean in the prototype scope is obtained through the container's getBean method;

 

request: For an HTTP request, only one instance of the bean in the request scope will be generated, which means that within the same HTTP request, every time the program requests the bean, it will always get the same instance. This scope is only really valid when using Spring in a web application;

 

For an HTTP session, a session-scoped bean will only generate one instance, which means that within the same HTTP session, every time the program requests the bean, it will always get the same instance. This scope is only really valid when using Spring in a web application;

 

global session: Each global HTTP Session corresponds to a Bean instance. Typically, this is only valid when using the portlet context, and also only valid in web applications.

 

If you do not specify the scope of the bean, Spring uses the singleton scope by default. The cost of creating and destroying beans in the prototype scope is relatively high. The singleton scope of the bean instance can be reused once the result is created. Therefore, you should try to avoid setting beans to prototype scope.

 

Injecting a collaborator bean using autowiring


 

 

Spring can automatically assemble the dependencies between beans, that is, it is not necessary to use ref to explicitly specify the dependent beans, but the Spring container checks the content of the XML configuration file, and injects the dependent beans for the caller bean according to certain rules. Spring autowiring can be specified through the element's default-autowire attribute, which works on all beans in the configuration file; it can also be specified through the element's autowire attribute, which only works on this bean.

 

autowire and default-autowire can accept the following values:


 

 

no: Do ​​not use autowiring. Bean dependencies must be defined through the ref element. This is the default configuration. Changing this configuration is discouraged in larger deployment environments. Explicitly configured partners can get clearer dependencies;

 

byName: Autowire based on the setter method name. The Spring container searches all beans in the container, finds the id and the setter method name, removes the set prefix, and lowercases the bean with the same name after the first letter to complete the injection. If no matching bean instance is found, Spring will not do any injection;

 

byType: Autowire based on the parameter type of the setter method. The Spring container searches all beans in the container. If there is exactly one bean type that matches the parameter type of the setter method, it will automatically inject the bean; if more than one such bean is found, an exception will be thrown; if no such bean is found , nothing will happen and the setter method will not be called;

 

constructor: Similar to byType, the difference is that it is used to automatically match the parameters of the constructor. If the container cannot find exactly one bean that matches the constructor parameter type, an exception will be thrown;

 

autodetect: The Spring container decides to use the constructor or byType strategy based on the internal structure of the bean. If a default constructor is found, then the byType strategy is applied.

 

When a bean uses both autowiring dependencies and explicitly specifies dependencies using ref, the explicitly specified dependencies override the autowiring dependencies; for large applications, autowiring is discouraged. While using autowiring reduces the workload of configuration files, it greatly defeats the clarity and transparency of dependencies. The assembly of dependencies depends on the attribute name and attribute type of the source file, which reduces the coupling between beans and beans to the code level, which is not conducive to high-level decoupling;

 

<!--The Bean can be excluded from autowiring by setting--><beanid=""autowire-candidate="false"/><!--In addition, it can also be specified in the beans element, support Pattern string, all beans ending with abc are excluded from autowiring --><beansdefault-autowire-candidates="*abc"/>

 

3 ways to create beans:


 

 

Create a Bean instance using the constructor


 

It is the most common situation to use the constructor to create a bean instance. If the constructor injection is not used, the bottom layer of Spring will call the parameterless constructor of the bean class to create an instance, so the bean class is required to provide a parameterless constructor.

 

The default constructor is used to create a Bean instance, and Spring performs default initialization on all properties of the Bean instance, that is, the values ​​of all basic types are initialized to 0 or false; the values ​​of all reference types are initialized to null.

 

Create beans with static factory methods


 

When using the static factory method to create a Bean instance, the class attribute must also be specified, but at this time the class attribute is not the implementation class of the specified Bean instance, but a static factory class. Spring knows which factory class to create the Bean instance through this attribute.

 

In addition, you also need to use the factory-method attribute to specify the static factory method. Spring will call the static factory method to return a Bean instance. Once the specified Bean instance is obtained, the subsequent processing steps of Spring are exactly the same as those of creating a Bean instance by ordinary methods. . If the static factory method requires arguments, use the <constructor-arg.../> element to specify the arguments to the static factory method.

 

Call the instance factory method to create a bean


 

There is only one difference between an instance factory method and a static factory method: calling a static factory method requires only the factory class, while calling an instance factory method requires a factory instance. When using the instance factory method, the <bean.../> element of the configuration bean instance does not need the class attribute, and the configuration instance factory method uses the factory-bean to specify the factory instance. When using the instance factory method to create a bean's <bean.../> element, you need to specify the following two attributes:

 

factory-bean: The value of this attribute is the id of the factory bean

 

factory-method: This attribute specifies the factory method of the instance factory

 

If you need to pass in parameters when calling the instance factory method, use the <constructor-arg.../> element to determine the parameter value.

 

Beans with unsynchronized coordination scopes


 

When a singleton-scoped bean depends on a prototype-scoped bean, there will be an asynchronous phenomenon, because when the Spring container is initialized, the container will pre-initialize all the singleton beans in the container. Since the singleton bean depends on the prototype bean, Therefore, Spring will create the prototypeBean before initializing the singleton bean - then create the singleton bean, and then inject the prototype bean into the singleton bean. There are two ways to resolve out-of-sync:

 

Abandon dependency injection: every time a singleton-scoped bean needs a prototype-scoped bean, it actively requests a new bean instance from the container to ensure that each injected prototype bean instance is the latest instance;

 

Using method injection: Method injection usually uses lookup method injection. Using lookup method injection allows the Spring container to rewrite the abstract or concrete methods of beans in the container and return the results of searching other beans in the container. The searched bean is usually a non-singleton Bean. Spring implements the above requirements by modifying the client's binary code using the JDK dynamic proxy or the cglib library.

 

The second approach is recommended, using method injection. In order to use the lookup method to inject, roughly the following two steps are required:

 

Define the implementation class of the caller bean as an abstract class, and define an abstract method to get the dependent Bean2. Add a <lookup-method.../> sub-element to the <bean.../> element to let Spring implement the caller bean The class implements the specified abstract method Notes;

 

Spring will use runtime dynamic enhancement to implement the abstract method specified by the <lookup-method.../> element. If the target abstract class has implemented the interface, Spring will use the JDK dynamic proxy to implement the abstract class, and for it Implement abstract methods; if the target abstract class has not implemented the interface, Spring will use cglib to implement the abstract class and implement abstract methods for it. The cglib class library has been integrated in the spring-core-xxx.jar package of Spring 4.0.

 

Two post processors:


 

 

Spring provides two commonly used post processors:

Bean post-processor: This post-processor will post-process the beans in the container and make additional enhancements to the beans;

Container Post-Processor: This post-processor will post-process the IoC container to enhance the container functionality.

 

Bean post processor


 

 

Bean post-processor is a special kind of bean. This special bean does not provide external services. It does not even need an id attribute. It is mainly responsible for performing post-processing on other beans in the container, such as generating the target bean in the container. Proxy, etc. This kind of Bean is called Bean post-processor. The Bean post-processor will further enhance the Bean instance after the Bean instance is created successfully. Bean post processor must implement the BeanPostProcessor interface, and must implement the two methods of the interface.

 

1.Object postProcessBeforeInitialization(Object bean, String name) throws BeansException: The first parameter of this method is the Bean instance that the system will post-process, and the second parameter is the bean's configuration id2.Object postProcessAfterinitialization(Object bean, String name ) throws BeansException: The first parameter of this method is the Bean instance that the system will post-process, and the second parameter is the bean's configuration id.

 

Once the bean post-processor is registered in the container, the bean post-processor will start automatically and work automatically when each bean in the container is created. The callback timing of the two methods of the bean post-processor is as follows

Note that if you use the BeanFactory as the Spring container, you must manually register the Bean post-processor, and the program must obtain an instance of the Bean post-processor, and then register it manually.

 

BeanPostProcessor bp = (BeanPostProcessor)beanFactory.getBean("bp");beanFactory.addBeanPostProcessor(bp);Person p = (Person)beanFactory.getBean("person");

 

container post processor


 

 

The bean post-processor is responsible for processing all bean instances in the container, while the container post-processor is responsible for processing the container itself. The container post-processor must implement the BeanFactoryPostProcessor interface, and implement a method of the interface postProcessBeanFactory (ConfigurableListableBeanFactory beanFactory). The method body that implements this method is the processing of the Spring container. This processing can be custom extended to the Spring container, of course. No processing is done to the Spring container.

 

Similar to BeanPostProcessor, ApplicationContext can automatically detect the container post-processor in the container, and automatically register the container post-processor. But if you use BeanFactory as the Spring container, you must manually call the container post-processor to handle the BeanFactory container.

 

Spring's "zero configuration" support


 

 

Search for Bean classes:


 

Spring provides the following Annotations to mark Spring Beans

@Component: Annotate a normal Spring Bean class

@Controller: annotate a controller component class

@Service: Annotate a business logic component class

@Repository: Annotate a DAO component class

Do the following configuration in the Spring configuration file to specify the automatically scanned package

<context:component-scan base-package="edu.shu.spring.domain"/>

 

Configure dependencies with @Resource


 

@Resource is located under the javax.annotation package. It is an annotation from the JavaEE specification. Spring directly borrows this annotation and uses this annotation to specify a collaborator bean for the target bean. Using @Resource has the same effect as the <property.../> element's ref attribute. @Resource can not only modify the setter method, but also directly modify the instance variable. If you use @Resource to modify the instance variable, it will be easier. At this time, Spring will directly use the JavaEE standard Field injection, and even the setter method can be omitted at this time.

 

Customize lifecycle behavior with @PostConstruct and @PreDestroy


 

@PostConstruct and @PreDestroy are also located under the javax.annotation package, and are also two Annotations from the JavaEE specification. Spring directly borrows them to customize the lifecycle behavior of beans in the Spring container. They are all used to decorate methods without any attributes. The method modified by the former is the initialization method of the bean; the method modified by the latter is the method before the bean is destroyed.

 

Spring 4.0 enhanced autowiring and precise wiring


 

Spring provides the @Autowired annotation to specify automatic wiring. @Autowired can modify setter methods, ordinary methods, instance variables, and constructors. When the setter method is annotated with @Autowired, the byType autowiring strategy is adopted by default. Under this strategy, there are often multiple candidate bean instances that conform to the type of automatic assembly, which may cause an exception. In order to achieve accurate automatic assembly, Spring provides the @Qualifier annotation. By using @Qualifier, it is allowed to use the id of the bean to perform automatic assembly.

 

Spring的AOP


 

 

Why do you need AOP?


 

AOP (Aspect Orient Programming) is also aspect-oriented programming. As a supplement to object-oriented programming, it has become a relatively mature programming method. In fact, AOP has not been around for a long time. AOP and OOP complement each other. Aspect-oriented programming decomposes the program running process into various aspects.

 

AOP is specially used to deal with the problems of cross concerns distributed in various modules (different methods) in the system. In JavaEE applications, AOP is often used to deal with some system-level services with cross-cutting properties, such as transaction management, security checking, Caching, object pool management, etc., AOP has become a very common solution.

 

Implementing AOP with AspectJ


 

AspectJ is an AOP framework based on the Java language, which provides powerful AOP functions. Many other AOP frameworks have borrowed or adopted some of these ideas. It mainly includes two parts: one part defines how to express and define the grammar specification in AOP programming. Through this set of grammar specifications, AOP can be easily used to solve the problem of cross concerns in the Java language; the other part is Tools section, including compilation, debugging tools, etc.

 

AOP implementations can be divided into two categories


 

1. Static AOP implementation: The AOP framework modifies the program during the compilation phase, that is, to enhance the target class and generate a static AOP proxy class, represented by AspectJ 2. Dynamic AOP implementation: The AOP framework dynamically generates AOP proxies during the runtime phase , to achieve enhancements to the target object, represented by Spring AOP

 

In general, static AOP implementations have better performance, but require the use of special compilers. Dynamic AOP implementations are pure Java implementations, so no special compilers are required, but generally have slightly worse performance.

 

Basic Concepts of AOP


 

 

Some Terminology About Aspect Oriented Programming

Aspect: Aspect is used to organize multiple Advice, and Advice is defined in the aspect;

 

Joinpoint: A clear point in the execution of a program, such as a method call or an exception thrown. In Spring AOP, a join point is always a method call;

 

Enhancement processing (Advice): The AOP framework performs enhancement processing at a specific pointcut. Handling has types such as "around", "before" and "after";

 

Pointcut: A join point where enhancement processing can be inserted. In short, when a connection point meets the specified requirements, the connection point will be added with enhanced processing, and the connection point will become the pointcut Spring's AOP support;

 

The AOP proxy in Spring is generated and managed by Spring's IoC container, and its dependencies are also managed by the IoC container. To use @AspectJ support in an application, Spring needs to add three libraries:

 

  • aspectjweaver.jar

  • aspectjrt.jar

  • aopalliance.jar

 

And do the following configuration in the Spring configuration file:

 

<!-- Start @AspectJ support --> 
< aop:aspectj-autoproxy />

<!-- Specify automatic search for bean components and automatic search for aspect classes --> 
< context:component-scanbase-package ="cn.javastack.service" >
     
   
<context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>
</context:component-scan>

 

Recommended in the past   


 

[1] Summary of Java Web technology experience

[2] 15 top Java multi-threading interview questions and answers, come and see

[3] Ten Java interview questions that interviewers like to ask

[4] Speak JAVA from scratch, giving you a clear learning path! Learn what to learn! !

[5] Welfare: 100G Java full set of learning videos are sent for free

 

My public number, welcome to pay attention! Get more technical dry goods!


 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325362186&siteId=291194637