A Brief introduction
1.Spring provides a lightweight solution for enterprise application development that includes core mechanisms based on dependency injection, declarative transaction management based on AOP, integration with multiple persistence layer technologies, and excellent web MVC frameworks. It can be said that spring is the "one-stop" choice of enterprise application development, which runs through the performance layer, the business layer and the persistence layer.
2. Download: http://projects.spring.io/spring-framework/
When using the spring framework, you must use the Spring core Container (the Spring container), which represents the core mechanism of the spring framework. Spring Core container mainly consists of Org.framework.core, Org.framework.beans, Org.framework.context, Org.framework.expression consists of four packages and their sub-packages, mainly supported by the spring IOC container.
Using the Spring Framework's Java Web project, you need to add the Spring Framework's jar packages and Commons-logging-1.1.3.jar to the Web-inf path of your web app.
3. Description
Lightweight: Spring is non-invasive, and objects in spring-based applications can be independent of spring's API
Dependency Injection (Di--dependency injection), controlled inversion (ioc--inversion of control)
Plane-oriented programming (Aop--aspect oriented programming)
Container: Spring is a container because it can contain and manage the life cycle of an Application object
Framework: Spring implements the combination of simple component configurations into a complex application that uses XML and Java annotations to combine these objects in spring
One-stop: open-source frameworks and excellent third-party libraries for enterprise applications can be consolidated on the basis of IOC and AOP
Two using spring to manage beans
The Spring core container theory is simple: the Spring core container is a super large factory where all objects (including data sources, Hibernate sessionfactory, etc.) are treated as objects managed by the spring core container. Spring will collectively refer to all objects in the container as bean,spring there is no requirement for the bean, as long as it is a Java class, spring can manage the Java class and treat it as a bean.
First, define a simple class Axe.java
public class Axe {
Public String Chop () {
Return "chopping wood with an axe";
}
}
Define a person class again
public class Perosn {
Private Axe Axe;
public void Setaxe (Axe Axe) {
This.axe=axe;
}
public void Useaxe () {
System.out.println ("going to firewood and firing");
System.out.println (Axe.chop ());
}
}
The Perosn object needs to invoke the method of the Axe object, which becomes a dependency.
Spring manages beans through an XML configuration file, example:
Establish Applicationcontext.xml under the project SRC
<?xml version= "1.0" encoding= "UTF-8"?>
<beans xmlns= "Http://www.springframework.org/schema/beans"
Xmlns:jaxws= "Http://cxf.apache.org/jaxws"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
Xmlns:util= "Http://www.springframework.org/schema/util"
xmlns:p= "http://www.springframework.org/schema/p"
xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.2.xsd
Http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
Http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd ">
<bean id= "Person" class= "Myspring.person" >
<property name= "Axe" ref= "Axe" ></property>
</bean>
<bean id= "Axe" class= "Myspring.axe"/>
</beans>
The <bean> element in the configuration file defaults to invoking the class parameterless constructor to create an instance, and the instance is configured as a bean in the Bean.zai spring configuration file in the Spring container. The value of the class attribute must be the full class name of the Bean implementation class (must have a package name), cannot be an interface, cannot be an abstract class (unless there is a special configuration), and spring cannot create an instance of the class with reflection.
The <property> child element drives spring to execute the setter method at the bottom with reflection, and the Name property value determines which setter method to execute, while value or ref determines the incoming parameter of the setter method. Once the bean is created, spring immediately executes the setter method based on the <property> child element. That is, the,<bean> element drives spring to call the constructor to create the object,<property> the child element drives the spring execution setter method, which is executed successively, with almost no gaps in the middle.
To access the bean in the container:
public class Test {
public static void Main (string[] args) {
ApplicationContext ctx=new classpathxmlapplicationcontext ("Applicationcontext.xml");
Perosn P=ctx.getbean ("person", perosn.class);
P.useaxe ();
}
}
The core mechanism of three spring--Dependency Injection
1. In Java applications there is a large number of cases where a object invokes the B object method, which is called dependency by spring, that is, the A object relies on the B object. The core features of the spring framework are two:
The spring container, as a super-large factory, is responsible for creating and managing all Java objects, which are called beans.
Spring containers manage dependencies between beans in a container through dependency injection
2. What is Dependency injection
When a Java object needs to invoke a method of another Java object, there are usually two practices in traditional mode:
Original procedure: The caller actively creates a method that is dependent on the object, that is, the new object, and then calls the object. There are two disadvantages to this approach: poor scalability, the need to modify the caller when the dependent object is modified, the caller also needs to care about the creation of the dependent object, in fact, it only needs to invoke some of these methods.
Simple Factory mode: The caller finds the factory where the object is being relied upon, and the method is called by the factory to fetch the dependent object. This mode should pay attention to three points: the caller is programmed for the interface of the dependent object, the creation of the dependent object is given to the factory, and the caller obtains the dependent component through the factory.
With the spring framework, the caller only needs to passively accept that the spring container assigns a value to the caller's member variable (to configure a <property> child element, spring executes the corresponding setter method to assign a value to the caller's member variable). Control inversion and dependency injection are two representations of the same behavior, only the angle of the description is different. Dependency injection usually has two ways:
Set value injection: The IOC container uses the setter method of the member variable to inject the dependent object.
Construct injection: The IOC container uses the constructor to inject the dependent object.
3. Attribute (set value) Injection:
Attribute injection is the most common injection method in practical application, which injects the bean's attribute value or dependent object through setter method.
Attribute injection uses the <property> element, using the Name property to specify the Bean's property name, the Value property, or the <value> child node to specify the property value
Construction Method Injection:
By constructing a method to inject the Bean's property value or dependent object, it ensures that the bean instance is instantiated and can be used
constructor injection in the <constructor-arg> element declaration attribute,<constructor-arg> No Name attribute
The Spring IOC container has three basic points:
(1) The components of the application are interface-oriented programming, so that the coupling relationship between components can be promoted to the interface level, which facilitates the later expansion.
(2) Each component of the application is no longer actively created by the program, but is generated and initialized by the spring container.
(3) Spring uses configuration files or annotations to manage the bean's implementation classes, dependencies, and the spring container uses reflection to create instances and inject dependencies into them based on the configuration file or annotations.
4. Construction Injection
Car.java
public class Car {
Private String brand;
Private String Corp;
private double price;
private int maxspeed;
Public Car (string brand, String Corp., double price) {
Super ();
This.brand = brand;
This.corp = corp;
This.price = Price;
}
@Override
Public String toString () {
Return "Car [brand=" + Brand + ", corp=" + corp + ", price=" + Price
+ ", maxspeed=" + Maxspeed + "]";
}
}applicationcontext.xml
<!--Configure the bean properties by constructing the method--
<bean id= "Car" class= "A.car" >
<constructor-arg value= "Audi" index= "0" ></constructor-arg>
<constructor-arg value= "Shanghai" index= "1" ></constructor-arg>
<constructor-arg value= "300000" index= "2" ></constructor-arg>
</bean>
Mytest.java:
public class MyTest {
public static void Main (string[] args) {
ApplicationContext ctx=new classpathxmlapplicationcontext ("A/applicationcontext.xml");
Car Car=ctx.getbean (Car.class);
SYSTEM.OUT.PRINTLN (car);
}
}
The essence of construction injection is to drive spring to execute the constructor with the specified parameters in the underlying reflection mode, and when the constructor with parameters is executed, the member variables can be initialized with the constructor parameters. That is, the difference between the setpoint injection and the constructor injection is that the value injection is to create a bean instance with a parameterless constructor and then invoke the corresponding setter method to inject the dependency, whereas the constructor injection calls the constructor with the argument directly, and when the bean instance is created, The injection of dependency has been completed.
If you add the following constructor to the Car.java, and you want to configure the Bean's properties through the constructor:
Public Car (string brand, String corp, int maxspeed) {
Super ();
This.brand = brand;
This.corp = corp;
This.maxspeed = Maxspeed;
}
The properties of the corresponding Bean are:
<bean id= "Car2" class= "A.car" >
<constructor-arg value= "Baoma" ></constructor-arg>
<constructor-arg value= "Shanghai" ></constructor-arg>
<constructor-arg value= "></constructor-arg>"
</bean>
Because there are two construction methods, the corresponding Test.java can only be used to locate the corresponding Bean with ID:
Car car= (CAR) ctx.getbean ("Car");
SYSTEM.OUT.PRINTLN (car);
Car car2= (CAR) ctx.getbean ("Car2");
System.out.println (CAR2);
The result: Car [Brand=audi, Corp=shanghai, price=300000.0, Maxspeed=0]
Car [Brand=baoma, Corp=shanghai, price=240.0, Maxspeed=0]
At this point two constructors will be ambiguous, only in order cannot be resolved. can be resolved by argument list, according to the number of parameters and parameter types to distinguish
<bean id= "Car2" class= "A.car" >
<constructor-arg value= "Baoma" type= "java.lang.String" ></constructor-arg>
<constructor-arg value= "Shanghai" type= "java.lang.String" ></constructor-arg>
<constructor-arg value= "type=" int "></constructor-arg>
</bean>
The result: Car [Brand=audi, Corp=shanghai, price=300000.0, Maxspeed=0]
Car [Brand=baoma, Corp=shanghai, price=0.0, maxspeed=240]
That is, using a constructor to inject property values can specify the number of parameters and the type of the parameter to differentiate the overloaded constructors
5. Comparison of two injection methods
Advantages of setting Value injection:
For complex dependencies, if you use construct injection, it can cause the constructor to be too bloated and difficult to read. When spring creates a bean instance, it needs to instantiate all of its dependent instances at the same time, causing performance degradation, and using set-value injection to avoid these problems.
Multi-parameter constructors are more cumbersome when some member variables are optional.
Advantages of Construction Injection:
The injection order of dependencies can be determined in the constructor, and priority injection is prioritized. Injections such as other dependencies in a component often need to rely on datasource injection.
Construction injection is more useful for beans that do not need to be changed by dependency relationships.
It is suggested that the injection strategy should be based on value injection and structure injection as a supplement.
Four Spring containers
The 1.Spring has two core interfaces: Beanfactory and ApplicationContext. Where ApplicationContext is the sub-interface of Beanfactory. They can all represent the spring container, the spring container is the factory that generates the bean instance, and the bean in the container is managed. Since ApplicationContext itself is a beanfactory sub-interface, ApplicationContext can be used entirely as a spring container, and more powerful, also known as the spring context.
The 2.BeanFactory common implementation class is Defaultlistablebeanfactory
The common implementation classes for ApplicationContext are:
Classpathxmlapplicationcontext: Loading a configuration file from a Classpath
Filesystemxmlapplicationcontext: Loading configuration files from the file system
Annotationconfigapplicationcontext
If you are using a spring container in a web app, there are typically Xmlwebapplicationcontext, annotationconfigwebapplicationcontext, and two implementation classes.
When you create an instance of a spring container, you must provide detailed configuration information for the spring container-managed bean, usually in an XML configuration file, so you should provide an XML configuration file as a parameter when creating an ApplicationContext instance. XML configuration files are typically passed in with resource objects.
The Beanfactory interface contains several basic methods:
Boolean Containsbean (String name): Determines whether the spring container contains a bean instance with ID name
<T> T Getbean (class<t> requiredtype): Gets the unique bean instance of the spring container that belongs to the Requiredtype type
Object Getbean (String name): Returns a bean instance with a container ID of name
<T> T Getbean (String name,class<t> requiredtype): Returns a bean instance with a container ID of name and a type of requiredtype
Class<?> GetType (String name): Returns the type of the bean instance with ID name in the container
ApplicationContext In addition to all the features supported by Beanfactory, it has the following additional features:
(1) By default, all singleton beans are pre-initialized, or they can be configured to cancel pre-initialization;
(2) Inherit the Messagesource interface, so it can provide internationalization support;
(3) resource access, such as access to URLs and files;
(4) the event mechanism;
(5) Loading multiple configuration files at the same time;
(6) Start and create the spring container declaratively.
When the system creates a ApplicationContext container, all singleton beans are pre-initialized by default. This means that there will be a significant overhead when creating applicationcontext in the early stages of the system, but once the ApplicationContext initialization is complete, there will be good performance when the Singleton Bean instance is fetched behind the program.
In general, for a normal bean, if there is no special configuration, the Bean is the singleton bean, if you do not want to pre-initialize the bean, you can specify lazy-init= "true" within the <bean> element
Spring Introductory One