Spring Learning (1)---IoC Introduction

An IOC overview
Ioc (Inversion of Control: Inverse of Control) is the core of the Spring container, and functions such as AOP. Declarative transactions blossom and bear fruit on this basis. The so-called inversion of control refers to the inversion of control of objects and classes to a third party, that is, the "dependency injection" proposed later.
1. Types of IoC Constructor
injection: Pass the interface implementation class into the constructor variable through the constructor of the class Attribute
injection: You can selectively complete the injection of dependencies required by the calling class through the Setter method, which is more flexible and convenient
 Interface injection (not commonly used): Extract all dependency injection methods of the calling class into an interface, and the calling class provides the corresponding injection methods by implementing the interface.

2. Complete dependency injection through the container
Spring container, which describes the dependencies between classes and classes through configuration files or annotations, and automatically completes class initialization and dependency injection. This frees the developer from the instantiation of these low-level implementation classes, the assembly of dependencies, and so on.

<!-- Implement class instantiation-->
<bean id="xxx" class="com.bao.xxx"/>
<!-- Build dependencies through xxx-ref-->
<bean id ="yyy" class="com.bao.yyy"p:xxx-ref="xxx"/>


Two java reflection mechanism

1. Simple instance
  In general, we will use the following code to create an instance of a class:
Car car = new Car();
//Car car = new Car("红旗");

The following is a more general way to indirectly manipulate the target class through the java emission mechanism
//Get the Car class object through the class loader
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Class clazz = loader.loadClass("com.baobaobao.reflect.Car");

// Get the default constructor object of the class and instantiate Car through it
Constructor cons = clazz.getDeclaredConstructor(Class[]null);
Car car = (Car)cons.newInstance();

//Set properties through reflection method
Method setBrand = clazz。getMethod("setBrand",String.class)
setBrand.invoke(car, "Benz");
......


2. Class Loader ClassLoader () The
class loader is the component that finds the section code file of the class and constructs the class to identify the object inside the JVM. In java, the class loader loads a class into the JVM and goes through the following steps:
1. Loading: Find and import Class files
2. Link: Perform verification, preparation and parsing steps, where the parsing step is optional:
   a) Verification: Check the correctness of the data loaded in the class file;
   b) Preparation: Allocate storage space for the static variables of the class;
   c) Analysis: Load the symbolic reference into a direct reference
3. Initialization: For the static variables of the class, static The code block performs the initialization work.

Important methods of ClassLoader
  • Class loadClass(String name) The name parameter specifies the name of the class that needs to be loaded by the class loader, and the class name must be determined using the permission. This method has an overloaded method loadClass(String name, boolean resolve), the resolve parameter is high whether the class loader needs to resolve the class.
  • Class defineClass(String name ,byte[] b,int off,int len) replaces the byte count assembly of the class file with the java.lang.Class object inside the JVM. Byte arrays can be fetched from the local file system, remote network. name is the fully qualified class name corresponding to the byte array
  • Class findSystemClass(String name) Loads the Class file from the local file system. If the class file does not exist in the local file system, a ClassNotFoundExecption exception will be thrown.
  • Class findLoadedClass(String name) Call this method to see if the ClassLoader has loaded a class.
  • ClassLoader getParent() Gets the parent loader of the class loader, except for the root loader (the root loader is not written in c++ by java)



3. Java reflection mechanism
  Class reflection object describes the semantic structure of the class, and can obtain the reflection objects of class elements such as constructors, member variables, method classes, etc. from the Class object, and operate the target class object through these reflection objects at the time of programming.
The three main reflection classes are:
  • Constructor: The constructor reflection class of the class, through the Class#getconstructors() method, you can get an array of all constructor reflection objects of the class. One of the main methods of Constructor is newInstance(Object[] initargs).
  • Method: The reflection class of the class method, through the Class#getDeclaredMethods() method, you can get all the methods of the class reflection class object array Method[]. The main method of Method is invoke(Object obj, Object[] args)
  • Method also has many methods for getting more information about a class method:
  • Class getRenturnType(): Get the return value type of the method;
  • Class[] getParameterTypes(): Get the input parameter type array of the method
  • Class[] getExceptionTypes(): Get the exception type array of the method
  • Annotation[][] getParameterAnnotations(): Get the annotation information of the method
  • Field: The reflection class of the member variable of the class, through Class#getDeclaredField(String name), you can get the reflection object of the member variable of a specific name.


Three resource access tools
1. Resource abstract interface
  Spring has designed a Resource interface, which provides applications with a stronger ability to access underlying resources. This interface has implementation classes corresponding to different resource types.
The main methods of the Resource interface:
  • boolean exists(): Whether the resource exists;
  • boolean isOpen(): Whether the resource is open;
  • URL getURL() throws IOExecption: If the underlying resource can be represented as a URL, this method returns the corresponding URL object;
  • File getFile() throws IOExecption: If the underlying resource corresponds to a file, this method returns the corresponding FIle object
  • InputStream getInputStream() throwsIOException: Returns the input stream corresponding to the resource.

  Resource plays an indispensable role in the Spring framework. The Spring framework uses Resource to load various resources, including configuration file resources, internationalization property file resources, and so on.




Assuming that there is a file in the classpath of the web application, the user can access this file resource in the following ways:
  • Access by FileSystemResource in the form of absolute path of the file system;
  • Access by classpath through ClassPathResource;
  • Access is relative to the web application root directory through the ServletContextResource.


Resource res1 = new FIleSystemResource("D:\workspace\test\WebRoot\WEB_INF\classes\1350775993.bmp">");

Resouces res2 = new ClassPathResource("1350775993.bmp");

Resources res3 = new ServletContextResource("","WEB_INF\classes\1350775993.bmp");


2. Resource loading
In order to access different types of resources, the corresponding Resource implementation class must be used, which is troublesome. Spring provides a powerful mechanism for loading resources, which can identify different resource types through "classpath:"."file:" and other Xiyuan address prefixes, and also supports Ant-style resource addresses with wildcards.



Ant-style resource qualification supports 3 matchers:
  • ? : matches a character in the filename;
  • *: matches any character in the file;
  • **: matches multi-layer paths.


The ResourceLoader interface of the resource loader has


only one getResource(String location) method, which can load file resources according to a resource address. However, the resource address only supports expressions with resource type prefixes, and does not support Ant-style resource path expressions. ResourcePatternResolver extends the ResourceLoader interface and defines a new interface method: getResources(String locationPattern), which supports expressions with resource type prefixes and Ant-style resource paths. PathMatchingResourcePatternResolver is a standard implementation class provided by Spring.
ResourcePatternResolver resolver new PathMatchingResourcePatternResolver();
Resource resources[] = resolver.getResources("classpath*:com/bao/**/*.xml");

Since the resource path is "classpath*:", PathMatchingResourcePatternResolver will scan all the paths in the classpath and the corresponding com.bao class package in the JAR package, and query all file resources with xml as the suffix.

Four BeanFactory and ApplicationContext
  Spring describes the dependencies between beans and beans through a configuration file, and uses the reflection function of java language to instantiate beans and establish dependencies between beans.
  Bean factory (com.springframework.br=eans.factory.BeanFactory) is the core interface of the Spring framework, which provides an advanced IoC configuration mechanism. BeanFactory makes it possible to manage different types of Java objects. The application context (com.springframework, context.ApplicationContext) is based on BeanFactory and provides more application-oriented functions. It provides internationalization support and framework event system, making it easier to Create municipal apps.
  For the purposes of the two, a simple division can be made: BeanFactory is the infrastructure of the Spring framework and is oriented to Spring itself; ApplicationContext is oriented to developers who use the Spring framework.

1. BeanFactory introduction
BeanFactory is a class factory, but different from the traditional annoying factory, the traditional class factory is only responsible for constructing one or several instances of the class. The BeanFactory is a generic factory for classes, which can create and manage a variety of tired objects. There is nothing special about these objects that can be created, but a POJO. Spring calls these created and managed Java objects Beans.

Class Architecture of BeanFactory
  Spring provides a variety of implementations for BeanFactory, the most commonly used is XMLBeanFactory.




The BeanFactory interface is located at the top of the class structure tree. Its main method is getBean(String beanName), which returns a Bean with a specific name from the container. The function of BeanFactory is continuously expanded through other interfaces.
  • ListableBeanFactory: This interface defines several methods for accessing the basic information of beans in the container, such as viewing the number of beans, obtaining the configuration name of a certain type of beans, etc.
  • HierarchicalBeanFactory: The interface of the parent-child cascade IoC container, the child container can access the parent container through the interface method;
  • ConfigurableBeanFactory: It is an important interface that enhances the customizability of the IoC container. It defines methods such as setting the class loader, property editor, and container initialization post-processing;
  • AutowireCapableBeanFactory: defines a method to automatically assemble beans in the container according to certain rules (such as name matching, type matching, etc.);
  • SingletonBeanRegistry: defines methods that allow singleton beans to be registered with the container during runtime;
  • BeanDefinitionRegistry: Each <bean> node element in the Spring configuration file is represented by a BeanDefinition object in the Spring container, which describes the configuration information of the Bean. The BeanDefinitionResgistry interface provides a method for manually registering BeanDefinition objects with the container.




Below the initialization of the BeanFactory
  , use the Spring configuration file to provide configuration information for Car, and then load the configuration file through the BeanFactory to start the Spring IoC container.

beans.xml:
<bean id="car1" class="com.baobaobao.Car"
  p:brand="奔驰" p:color="black" p:maxSpeed="200"/>


BeanFactoryTest
//Start the SpringIoC container through the XmlBeanFactory implementation class
ResourcePatternReslver resolver = new PathMatchingResourcePatternResolver();
Resource res =resolver.getResource("classpath:com/baobaobao/beanfactory/beans.xml");
BeanFactory bf = new XmlBeanFactory(res);
Car car = bf.getBean("car",Car.class);



  XmlBeanFactory loads Spring configuration information through Resource and starts the IoC container, and then the Bean can be obtained from the IoC container through the BeanFactory#getBean(beanName) method. When the IoC container is started through the BeanFactory, the Bean defined in the configuration file will not be initialized. The initialization action occurs when the first call is made. For a single-instance (singleton) Bean; BeanFactory will cache the Bean instance. The next time you use getBean() to get a bean, it will directly get the bean instance from the cache of the IoC container.

2.ApplicationContext introduction
  ApplicationContext is derived from BeanFactory, which provides more practical application-oriented functions.

ApplicationContext class architecture
  The main implementation classes of ApplicationContext are ClassPathXmlApplicationContext and FileSystemXmlApplicationContext.




ApplicationContext initialization
//equivalent to classpath:com/baobaobao/context/beans.xml
ApplicationContext ctx = new ClassPathXmlApplicationContext("com/baobaobao/context/beans.xml");

//ApplicationContext ctx = new FileSystemXmlApplicationContext("com/baobaobao/context/beans.xml");等同于file:com/baobaobao/context/beans.xml


A POJO annotated with @Configuration can provide the bean configuration information required by Spring:
//Indicates that it is a configuration information provider class
@Configuration
public class Beans{
  // set to a bean
  @Bean(name="car")
  public Car buildCar(){
    Car car=new Car();
    car.set...
    ...
  }
}


  Spring provides a special ApplicationContext implementation class for annotation-based configuration: AnnotationConfigApplicationContext.

ApplicationContext ctx = new AnnotationConfigApplicationContext(Beans.class);
Car car=ctx.getBean("car".Car.class);


WebApplicationContext class architecture
 


ConfigurableWebApplicationContext extends WebApplicationContext, which allows instantiation of WebApplicationContext through configuration, which defines two methods;
  • setServletContext(ServletContext servletContext): Sets the web application context for Spring
  • setConfigLocations(String[] configLocations): Set the Spring configuration file address.


WebApplicationContext initialization
  WebApplicationContext initialization requires a ServletContext instance, which means that it must have a Web container to complete the startup work. Configure self-starting servlets in web.xml or define web container listeners (ServletContextListener)

<!-- Load the Spring configuration file from the classpath, load the specific classpath of the classpath keyword -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	<!-- The listener responsible for starting the Spring container, it will refer to the context parameter at context-param to obtain the address of the Spring configuration file -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326894785&siteId=291194637