Spring is a lightweight solution for the development of enterprise applications. Includes core mechanisms based on dependency injection, declarative transaction management based on AOP, integration with multiple persistence layer technologies, and excellent web MVC frameworks. Spring runs through the presentation layer, the business layer, and the persistence layer.
Spring Benefits: Low-invasive design code is low in pollution. Independent of the various application servers. Spring's IOC container reduces the complexity of business object substitution and improves decoupling between components. Spring's AOP support allows a number of common tasks such as security, things, logs, and so on to be centrally processed to provide better reuse. Spring's ORM and DAO provide a good integration with the Third-party persistence layer framework, simplifying the underlying database access. Spring's high openness does not emphasize the application being completely dependent on spring, and the developer is free to choose the required parts.
The following figure is the composition chart of the spring framework
Spring Management Bean
Use Spring management bean,spring to collectively refer to all objects in a container as beans. Spring has no requirements for beans, as long as it is a Java class. So all the objects are beans. Spring uses configuration file management.
Pseudo code Fragment
Configuration in XML
<bean id = "" class = "" >
<property name = "" VALUE = "" ref = "" >
//Implementation
at the bottom of spring String id = "";
Class clazz = Class.forName (CLASSSTR);
Object obj = clazz.newinstance ();
Container.put (ID, obj);
String name = "";
String ref = "";
String classstr = "";
String settername = "Set" +name.substring (0,1). toUpperCase () +name.substring (1);
Object param = container.get (ref);
Method setter = Clazz.getmethod (Settername, Param.getclass ());
Setter.invoke (obj, param);
When you configure a bean in the spring configuration file, the value of the class attribute must be the full class name of the Bean implementation class, cannot be an interface, cannot be an abstract class, or spring cannot use the launch to create an instance of the class. The bean element drives the spring call constructor, which is the default driver spring, which invokes the parameterless constructor creation object at the bottom, property-driven spring executes the setter method, The Name property value determines which setter method to perform (so the value of name corresponds to the property value in Java code), and value or ref determines the parameter value that is passed in. These two steps are executed successively, with almost no interval between them. using the spring container in your program
ApplicationContext is the most common interface for spring containers, which has two common implementation classes: Classpathxmlapplicationcontext: Searches for configuration files from the class load path and creates a spring container based on the configuration file. Filesystemxmlapplicationcontext: Searches the configuration file from the relative or absolute path of the file system, and creates the spring container based on the configuration file.
ApplicationContext CTX = new Classpathxmlapplicationcontext ("Bean.xml");
Object obj = Ctx.getbean ("", xx.class);//causes the program not to create Java objects using the new call constructor, all Java objects are created by spring
Spring Core mechanism: Dependency Injection
Also known as control reversal (IOC) or Dependency injection (DI), after using the spring framework, the caller acquires the dependent object by the original active acquisition, which becomes passive acceptance. So, call control reversal. From the container's point of view, the spring container is responsible for assigning the dependent object to the caller's member variable, which is equivalent to injecting the caller with an instance of its dependency.
Major changes after using the Spring framework: programs do not need to create objects using new. When you want to invoke a method of a dependent object, the caller does not have to actively acquire the dependent object, just wait for the spring
The container can be injected.
three basic points for using the Spring IOC container : interface-oriented programming for each component of the application. Application-level components are no longer actively created by programs spring uses configuration files or annotations to manage bean implementation classes, dependencies, and the spring container creates and injects dependencies based on the configuration file or annotation, using reflection to create the instance.
There are usually two types of dependency injection :
-Set value injection: Using the setter of the member variable to inject the dependent object
-Constructed injection: The constructor is used to inject the dependent object. Constructor-arg to represent the construction parameters
difference : Set-value injection first creates a bean instance through an parameterless constructor and then invokes the corresponding setter method to inject the dependency; the constructed injection is a direct invocation of the parameter construct, and the dependency injection has been completed when the bean instance is created. Finally, it is suggested to adopt the strategy of setting value injection as the main and constructing injection as supplement. For dependencies without changing the injection, as far as possible using structural injection. using the Spring container
Spring has two and new interfaces: Beanfactory ApplicationContext
The ApplicationContext is a beanfactory sub-interface. Spring is the factory that generates the beans and manages the beans.
* * Difference **beanfactory does not pre-initialize the Bean,applicationcontext in the container automatically initializes the singleton Bean in the container, or it can manually cancel the initialization. Therefore, the system early in the creation of ApplicationContext cost is relatively large, but once the initialization is completed, the program to obtain singleton bean performance improvement. The use of ApplicationContext is generally recommended. the event mechanism of ApplicationContext
The event mechanism of ApplicationContext is the realization of the observer design pattern, and the ApplicationContext event processing can be realized through Applicationevent class and Applicationlistener class interface. Applicationevent Container event, the Applicationlistener listener must be published by ApplicationContext, and can be served by any listener bean in the container
The event mechanism consists of event sources, events, and event listeners. The Applicationcontex is an event source and the event must be explicitly triggered by the Java program. scope of Bean in container
When you create a bean instance from spring, you can not only complete the bean instantiation but also specify the scope for the bean. There are 5 scopes: Singleton singleton mode, which will generate only one bean instance throughout the container, which is responsible for maintaining the bean lifecycle. Once the creation is successful, it can be reused. Prototype gets a new instance each time it is fetched through the container, and once the creation succeeds, the container will no longer be responsible for its lifecycle. The cost of creating a destruction is greater. Request sessions for HTTP requests one time for HTTP conversation global session only in Web applications does this function effectively use automatic assembly to inject the partner Bean
Spring's automatic assembly can be specified by the Autowire property, which only works for all beans in the configuration file, which is acceptable: Bytype: Automatic assembly based on the parameters of the setter Method ByName: Automatic assembly based on setter method name, If more than one such bean is found, an exception is thrown, and nothing happens if it is not found. Constructor: Similar to Bytype, the difference is the parameters of the constructor used for automatic matching. If no such bean is found, an exception is thrown. The Autodetect:spring container decides to use constructor or Bytype policies based on the internal structure of the bean. If a default constructor function is not found, the bytype is applied. Spring's beans and JavaBean
The spring container has no special requirements for beans, and does not even require that the bean like standard JavaBean must provide the appropriate setter and getter methods for each property. The beans in spring are Java instances, Java components, whereas traditional javabean are used as DTO (data transfer objects) to encapsulate value objects and pass data between tiers.
the beans in spring should satisfy several principles : as much as possible to provide a parameterless constructor for each bean implementation class to accept the constructed injection of the bean, you should provide the corresponding setter method by supplying a bean with the parameter's constructor acceptance value injection. There is no need to provide the appropriate getter method
The difference between traditional javabean and Bean in spring: the use is different: traditional JavaBean more as a value object passing parameters; spring's beans are useful everywhere, and any application component is called a bean. Different writing: traditional JavaBean as a value object requires getter and setter methods for each property, but spring's beans simply provide setter methods for properties that accept settings injection. The lifecycle is different: the traditional javabean is passed as a value object and does not accept any container to manage its lifecycle; The Bean in spring manages its lifecycle behavior by spring. How to create a bean call constructor Create Bean call static Factory method Create Bean Call Instance Factory method Create Bean Call static Factory method Create Bean Class attribute must also be specified, But at this point the class attribute is not the implementation class for the specified bean instance, but the static factory class. Spring uses this property to know which factory class to create the bean instance. The Factory-method property specifies that the static factory method returns a bean instance.
When a static factory method creates a bean instance, spring can still manage the dependencies of the bean instance, including injecting the required bean and manager lifecycle into it. To invoke the instance factory method to create a bean
The instance factory method differs from the static factory method: Configure the static factory method to specify the static factory class using Class, while the configuration instance factory method uses Factory-bean to specify the factory instance. When using the instance factory method, the bean element that configures the bean instance does not require a class attribute because the spring container does not directly instantiate the Bean,spring container to invoke only the instance factory method, and the factory method is responsible for creating the bean instance. Factory-bean factory-method Difference
Call the static factory method to create the bean and invoke the instance factory method to create the bean, in the same place :
-All need to use Factory-method
-factory method specifying parameter values with the CONSTRUCTOR-ARG element if you need to use parameters
-Normal setting injection, using property to determine the value of the parameter
different : Configure the instance factory method to create the bean, the instance factory must be configured as a bean instance, and a static factory method is configured to create the bean without configuring the factory bean.
Configure the instance factory method to create the bean, you must use the Factory-bean property to determine the factory bean, while the static factory method is configured to create the bean, the static factory class is determined using the class element. Abstract bean and child bean
Extracts the same information from multiple bean element configurations and centralizes the configuration template, which is not a real bean and needs to be increased abstract=true, which is the abstract bean. Abstract beans cannot be instantiated, the spring container does not create an abstract bean instance, t its value is inherited, so you can not specify the class attribute.
A child bean can specify its parent's bean through the parent property, overwriting the parent bean when the configuration information that the child bean refers to is inconsistent with the parent bean. the difference between bean inheritance and Java inheritance
The former is general to special refinement, and the latter is the continuation of parameter values between instances and instances. The former is the relationship between class and class, and the latter is the relation between object and object. difference : A child bean in spring cannot be used as a parent bean and does not have polymorphism; the main manifestation in the polymorphism spring in Java is that the parameter is worth extending, while the main manifestation of Java is the continuation of method and attribute. The child beans in spring can be different types from the parent bean, whereas in Java you can guarantee that subclasses are special types of the parent class. the factory bean in the container
This factory bean must implement the Factorybean interface, after the factory bean is deployed in the container, and if it is obtained through Getbean, the container returns not the Factorybean implementation class but the product that returns Factorybean.
The value of implementing the Factorybean interface: The spring container does not simply return the instance but returns the return value of the GetObject method of the Bean instance, which is implemented by the developer. the life cycle of beans in a container
Spring can manage the lifecycle of a singleton-scoped bean, knowing exactly when the bean was created, when it was initialized, and when the container was ready to destroy the bean instance.
Spring for the prototype scope is only created, and after the container has created the bean, it is completely left to the client management, and the container does not track its lifecycle.
For singleton scopes, spring can manage the behavior of the instantiation and before it is destroyed, with two main opportunities: after injecting the dependencies
Provides two ways to perform a specific behavior: using the Init-method property; before the implementation of the Initializingbean interface is about to be destroyed
Provides two ways to perform a specific behavior: using the Destroy-method property; implementing the Disposablebean interface
Summary
The essence of spring is to execute Java code through an XML configuration, so almost all Java code can be managed in the spring configuration file. Calls the constructor to create the object, invokes the setter method with the bean element, invokes the getter method with the property element, and invokes the normal method with the Propertypathfactorybean or util:property-path element. Gets the value of the field with the Methodinvokeingfactorybean factory bean, using the Fieldretrievingfactorybean or util:constant element
the role of the Spring IOC container : The coupling of the original Java code management is extracted into the XML for management, thus reducing the coupling between the components and improving the maintainability of the system.