1 Basic Spring Features
Spring is a very active open source framework; it is a framework that builds multi-layer JavaEE systems based on Core, and its main purpose is to simplify enterprise development.
Spring manages your code in a non-invasive way. Spring advocates "minimum intrusion", which means you can install or uninstall Spring at the appropriate time, and Spring makes Java bright. (Open and closure principle), here is the closing principle.
2. Tools required to develop spring
(Here we first select spring 2.5 and then 3.0)
2.1 Spring's jar package
Download spring at http://www.springsource.org/download, then decompress, find the following jar file in the decompression directory, and copy it to the classpath
―The core class library of spring is dist/spring.jar under dist in spring document
―The third-party library introduced is all spring document under lib, lib/jakarta-commons/commons-logging.jar
―If the aspect programming (AOP) is used, the following jar files lib/aspectj/aspectjweaver.jar and aspectjrt.jarlib/cglib/cglib-nodep-2.1_3.jar are also required
―If you use the annotations in JSR-250, such as @Resource/@PostConstruct/@PreDestroy, the following jar file lib/j2ee/common-annotations.jar is also required
Note: JSR (Java Specification Request) refers to a formal request to add a standardized technical specification to JCP (Java Community Process). Anyone can submit a JSR (Java specification request) to add new APIs and services to the Java platform. JSR has become an important standard in the Java world
2.2 Spring configuration file
By default it is the applicationContext.xml file. Many xml files can be created, and this is generally configured in projects. (Created in the src directory)
3 Detailed explanation of the basic functions of Spring
3.1 SpringIOC
Spring's control inversion: hand over the creation, initialization, destruction and other tasks of objects to the spring container. Controls the life cycle of an object by the spring container.
step:
•A. Start the spring container
1. Find configuration files in the classpath to instantiate the container
The code copy is as follows: ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
You can look for xml files in the entire classpath
* Load this way. You need to put the spring configuration file under the classpath path of the current project
* classpath path refers to the src directory of the current project, which is the storage location of the java source file.
2. Find configuration files in the file system path to instantiate the container
Spring's configuration file can specify multiple configuration files and can be passed in through String arrays.
Note: Use the first method to start the container often
•B. Extract objects from spring container
spring container structure:
3.2 Alias
<beans> <alias name="person" alias="p"///alias is an alias, you can get the person bean through p. <bean name="person"/></beans>
With such a configuration, the effect of naming in one place and using different names in multiple places can be achieved.
3.3 Spring container internal objects
1 How to create an object
1.1 No parameter constructor
<bean id="helloWorld"></bean>
1.2 Static factory method
<bean id="helloWorld2"
factory-method="getInstance"></bean>
1.3 Example factory method
<bean id="helloWorldFactory"></bean>
<bean id="helloWorld3" factory-bean="helloWorldFactory" factory-method="getInstance"></bean>
Just remember the concept. The first method is the most used, but when integrating with other tools, the instance factory model is used.
Example :
Configure applicationContext.xml
<?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-2.5.xsd"> <!-- Put a class into a spring container, the class is called a bean --> <!-- Bean describes a class id The unique full name of the class class --> <bean id="helloWorld"></bean> <!------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- factory-method="getInstance" ></bean><!--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Create entity class HelloWorld
package com.itheima10.spring.createobject;public class HelloWorld { public void hello(){ System.out.println("hello"); }}Establish a static factory HelloWorldFactory
package com.itheima10.spring.createobject.method;public class HelloWorldFactory { public static HelloWorld getInstance(){ System.out.println("static method"); return new HelloWorld(); }}Establish a physical factory HelloWorldFactory2
package com.itheima10.spring.createobject.method;public class HelloWorldFactory2 { /** * The factory object must be created before the method can be called* @return */ public HelloWorld getInstance(){ return new HelloWorld(); }}Write test method CreateObjectMethodTest
package com.itheima10.spring.createobject.method;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * It is OK to see the second and third generation methods * @author zd * */public class CreateObjectMethodTest { /** * By default, the spring container calls the default constructor of a class to create an object*/ @Test public void testCreateObject_Default(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorld"); helloWorld.hello(); } /** * Create an object using a static factory* <bean id="helloWorld2" factory-method="getInstance" ></bean> What the spring container does: The getInstance method is called using the HelloWorldFactory class*/ @Test public void testCreateObject_StaticFactory(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorld2"); helloWorld.hello(); } /** * Instance factory method creates an object* <bean id="helloWorldFactory" *></bean> * <bean id="helloWorld3" factory-bean="helloWorldFactory" factory-method="getInstance"></bean> What to do inside the spring container: 1. Create a helloWorldFactory object 2. Call getInstance from this object to generate a helloWorld object*/ @Test public void testCreateObject_InstanceFactory(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorld3"); helloWorld.hello(); }}2 scope of object
The scope of an object has two properties: singleton and prototype. Singleton means singleton
2.1 singleton (default value)
In each Spring IoC container, there is only one object instance (shared).
2.2 prototype
Allowing beans to be instantiated multiple times (create one instance once is used). Spring cannot be responsible for the entire life cycle of a prototype bean. This means it is the responsibility of the client to be clear about the prototype scoped objects and to free up the expensive resources held by any prototype bean.
<bean id="helloWorld" scope="singleton"></bean>
<bean id="helloWorld" scope="prototype"></bean>
Create HelloWorld class
public class HelloWorld { public List<String> lists = new ArrayList<String>(); public HelloWorld(){ System.out.println("new instance"); } public void hello(){ System.out.println("hello"); }}Create a test class ScopeTest
package com.itheima10.spring.scope;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class ScopeTest { /** * Put a bean into the spring container, the default is a singleton* If a class is placed in the spring container and this class is a singleton, then the properties in the class will become shared*/ @Test public void testCreateObject_Scope_Default(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); HelloWorld hello1 = (HelloWorld)context.getBean("helloWorld"); hello1.lists.add("aaaa"); hello2= (HelloWorld)context.getBean("helloWorld"); hello2.lists.add("bbbb"); System.out.println(helloWorld.lists.size()); //2, and only output new instance } /** * If spring's configuration file is as follows: * <bean id="helloWorld" scope="prototype"></bean> Then the spring container will create multiple objects for */ @Test public void testCreateObject_Scope_Prototype(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); HelloWorld hello1 = (HelloWorld)context.getBean("helloWorld"); hello1.lists.add("aaaa"); hello2= (HelloWorld)context.getBean("helloWorld"); hello2.lists.add("bbbb"); System.out.println(helloWorld.lists.size());//1, and only output new instance }}3 Initialization time
Lazy loading - by default, the bean will be initialized when the container starts, but we can specify the lazy-init="true" of the bean node to delay the initialization of the bean. At this time, the bean will be initialized only if the bean is retrieved for the first time. like:
<bean id="xxx" lazy-init="true"/>
If you want to apply delayed initialization to all beans, you can set default-lazy-init="true" in the root beans, as follows:
<beans default-lazy-init="true" ...>
Spring instantiates all singleton beans in advance at startup by default. Early instantiation means that as part of the initialization, the ApplicationContext automatically creates and configures all singleton beans. This is usually a good thing. Because in this way any errors in the configuration can be discovered immediately.
Lazy-init is false, spring container will report an error when it is started (a better way)
Lazy-init is true, and the spring container will make an error when calling the class.
Configure applicationContext.xml
<bean id="helloWorld" scope="prototype"></bean></beans>
Create test class CreateObjectWhenTest
package com.itheima10.spring.createobject.when;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class CreateObjectWhenTest { /** * Order by default* 1. Start spring container* 2. Create HelloWorld object* 3. Object calling method* * <bean id="helloWorld"></bean> <bean id="helloWorld2"></bean> Because two beans are declared in the spring container, the spring container needs to create two objects: If struts2, hibernate, and spring containers are integrated, if an error occurs in the spring configuration file, an error will be reported when the tomcat container is started, and the error will be displayed particularly early. If a bean stores a large amount of data, this method is not good, and the data may be stuck in memory too early. If a bean is not a singleton, no matter how it is configured, the object must be created when it is a context.getBean*/ @Test public void testCreateObject_When_Default(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); context.getBean("helloWorld"); } /** * <bean id="helloWorld" lazy-init="true"></bean> * Order* 1. Start the spring container* 2. context.getBean * 3. Call the constructor function to create an object* Description: If struts2, hibernate, spring containers are integrated, if an error occurs in the spring configuration file, an error will only be reported when the bean is used. If a bean stores a large amount of data, it is necessary to load data when needed*/ @Test public void testCreateObject_When_Lazy(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); context.getBean("helloWorld"); }}4 init, destroy methods
When Spring initializes beans or destroys beans, some processing is sometimes required, so spring can call the two lifecycle methods of the bean when creating and disassembling beans. You can specify a method to operate.
<bean id="foo" class="...Foo" init-method="setup" decoration-method="teardown"/>
Call the init-method method when foo is loaded into the Spring container. Calling deployment-method when foo is deleted from container (scope = singleton valid)
Writing HelloWorld
public class HelloWorld { public HelloWorld(){ System.out.println("new instance"); } public void init(){ System.out.println("init"); } public void destroy(){ System.out.println("destroy"); } public void hello(){ System.out.println("hello"); }}Write test class InitDestroyTest
package com.itheima10.spring.ioc.initdestroy;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class InitDestroyTest { /** * init-method="init" * Execution order: * 1. Start the spring container* 2. Create helloWorld object* 3. Execute init method* Automatic execution within the spring container* 4. Object calling method* 5. The destroy method can only be executed when the spring container is closed: the bean is a singleton* This method is also called internally by the spring container* Description: * If a bean is not a singleton, the spring container is not responsible for the object destruction. * In the spring container, only if one bean is a singleton, the spring container is responsible for the creation, initialization and destruction of objects* If a bean is not a singleton, the spring container is only responsible for the creation and initialization*/ @Test public void testInitDestroy(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorld"); helloWorld.hello(); ClassPathXmlApplicationContext applicationContext = (ClassPathXmlApplicationContext)context; applicationContext.close(); }} Execution sequence diagram:
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.