The core technology of the Spring Framework

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_43378945/article/details/102657414

Overview Spring
 Spring is a layered Java SE / EE applications stop lightweight open-source framework. Spring is the core of IOC and AOP.
Spring Key benefits include:

  1. Decoupling easy, simplifying the development, the IoC container provided by Spring, we can rely on the relationship between objects referred Spring controlled, high coupling procedures to avoid hard-coded result.
  2. AOP programming support, AOP functionality provided by Spring, convenient Oriented Programming.
  3. Support for declarative transactions, in Spring, we can free from the monotonous boredom of transaction management code, to manage transactions through a declarative way flexibility, improve development efficiency and quality.
  4. Convenient test procedure can be carried out almost all of the testing container with a non-programming-dependent manner.
  5. Easy integration of a variety of excellent framework, Spring provides direct support for a variety of excellent framework.
    Spring architecture
    throughout the spring frame according to their respective functions can be divided into five main modules, five modules provides almost everything needed for enterprise applications, from the persistence layer, the business layer to the presentation layer all with appropriate support, which is Spring is the reason why the said stop frame.
    Here Insert Picture Description
    1. Core Module (Core Container)
    the Spring core module implements IOC function dependencies between classes and disengaged it from the code out of dependency relationships described by way of configuration. Create a container by the IOC in charge of the class, management, acquisition and so on. BeanFctory interface is the interface to the core Spring framework to achieve a lot of the core vessel function.
    Context module is built on the core module extends the functionality of BeanFactory. ApplicationContext Interface Context is the core module.
    Expression Language (Expression Language) is an extension of the unified expression language (EL) to support the set and get object properties, call the object methods manipulate arrays, collections and so on. Use it to easily interact through the expressions and Spring IOC container.
    2.AOP module
    Spring AOP module is provided which satisfies the AOP Alliance specifications, which also incorporates a framework AOP AspectJ language level. AOP can be reduced by coupling.
    Access data integration module (Data Access / Integration)
    The module includes a JDBC, ORM, OXM, JMS and transaction management:
    1. Transaction Module: This module Spring Management, as long as it can get Spring Spring managed object management services benefits, without the need for transaction control, and it supports transaction management and declarative programming code.
    2.JDBC Module: provides a JBDC sample templates, use these templates eliminate the traditional tedious JDBC coding as well as transaction control must, and can enjoy the benefits of Spring managed transactions.
    3.ORM module: provides popular - seamless integration "object relation" mapping framework, including hibernate, JPA, MyBatis like. And you can use Spring transaction management, without additional control transactions.
    4.OXM module: provides a mapping to achieve Object / XML, Java object to an XML mapping data, or XML data into mapped java object, Object / XML mapping implementations include JAXB, Castor, XMLBeans and XStream.
    5.JMS module: for JMS (Java Messaging Service), providing a "message producers, message consumers" template for simpler use JMS, JMS is used between two applications, or distributed systems send messages, asynchronous communication.
    Web module
      The module is built on top of ApplicationContext module that provides the functionality of Web applications, such as file upload, FreeMarker and so on. Spring MVC frameworks such as Struts2 can be integrated. Furthermore, Spring provides its own MVC framework Spring MVC.
      Test module
      Spring can be almost all the testing container with a non-programming-dependent manner, and support TestNG JUnit test frameworks.
      Acquaintance IOC and DI
      1, DI IoC inversion of control and dependency injection
      method traditional programming, we need to use an object, you need to create the object by a new, this time we are proactive behavior; and we will IoC creating an object control to the IoC container, then by container to help create and inject dependent objects, our program passively accept the IoC container to create objects, control reversal, so called inversion of control.

Since IoC really not enough straight to the point, it is proposed DI (Dependency Injection: Dependency Injection) concept that allows third parties to achieve injection to remove dependencies between classes and class we need to use. Overall, ** IoC is the goal, DI is a means, ** often means the process of creating an object dependency injection. In order to achieve our IoC, so that the object is generated by the way the traditional way (new) upside down, when you need to create related objects help us by the IoC container injection (DI).

Simply put, what we need another class in the class, just let us help create the Spring, this is called inversion of control; then Spring will help us to set up the required objects in our class, which is called dependency injection.
  2. several common injection method
  using the injection method has a configuration parameter

public class  User{
    private String name;
    public User(String name){
        this.name=name;
    }
} 

    User user=new User("tom");

Use property injection

public class  User{
    private String name;
    public void setName(String name){
        this.name=name;
    }
}

     User user=new User();
     user.setName("jack");

Use interface injection

// 将调用类所有依赖注入的方法抽取到接口中,调用类通过实现该接口提供相应的注入方法。 

public interface Dao{
    public void delete(String name);
} 

public class DapIml implements Dao{
    private String name;
    public void delete(String name){
        this.name=name;
    }
}

The container is completed by injecting dependencies

Above all we need a manual injection method of implanting, if there is a third party vessel to help us complete instantiation of the class , and the dependencies of the assembly, then we only need to focus on business logic can be developed. Spring is such a vessel, through which the configuration file dependencies between classes and class description or annotations, class initialization and auto-complete dependency injection work.
IOC 3.Spring example of
(1) to create a project, import the jar package

Here we just do IoC operation, so only need to import the core module in a jar, beans, core, context, expression and so on. Because the relevant jar package spring and no log, so we also need to import log4j and commons-logging.

(2) create a class

 public class User {
    public void add(){
        System.out.println("add.....");
    }
}

(3) create a xml configuration file

<?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.xsd"> 

    //配置要创建的类  
    <bean id="user" class="com.cad.domain.User"/>        
</beans>  

(4) test

 //这只是用来测试的代码,后期不会这么写
public class Test {

    @org.junit.Test
    public void test(){
        //加载配置文件
        ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
        //获取对象
        User user=(User) context.getBean("user");
        System.out.println(user);
        //调用方法
        user.add();
    }
} 

When the container starts, Spring description information based on the profile, and automatically instantiates Bean complete the assembly of dependencies, can be obtained from the container Bean instance, it can be used directly. Spring Why do alone a simple configuration file, you can instantiate and configure magical Bean good program to use it? The answer is through the Java reflection technology.

DI 4.Spring example of
 our service layer is always used dao layer, we used to always new objects in a dao Service layer, and now we use dependency injection ways to inject dao layer Service layer.

// UserDao
public class UserDao {
    public void add(){
        System.out.println("dao.....");
    }
}

// UserService
public class UserService {
    UserDao userdao;
    public void setUserdao(UserDao userdao){
        this.userdao=userdao;
    }

    public void add(){
        System.out.println("service.......");
        userdao.add();
    }
}

-------------------------------分割线--------------------------

// 配置文件
<bean id="userdao" class="com.cad.domain.UserDao"></bean> 
//这样在实例化service的时候,同时装配了dao对象,实现了依赖注入
<bean id="userservice" class="com.cad.domain.UserService">
    //ref为dao的id值
    <property name="userdao" ref="userdao"></property>
</bean>

Spring's Ioc container Detailed
1.BeanFactory
  BeanFactory is a factory class, different from traditional class factory, the conventional configuration of a class factory is responsible for only a few class instance or class; BeanFactory can create and manage the various types of objects, Spring these are called to create and manage Java objects to Bean.

BeanFactory is an interface, Spring provides a variety of implementations for the BeanFactory, the most common is XmlBeanFactory. Which, BeanFactory most important is the interface method getBean (String beanName), which returns Bean specified name from the container. Further, BeanFactory interface function can be extended (for example, the ApplicationContext) implemented by its interface. See the following example:

//我们使用Spring配置文件为User类提供配置信息,然后通过BeanFactory装载配置文件,启动Spring IoC容器。 
<?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.xsd">

<bean id="user" class="com.cad.domain.User"></bean>   
</beans>  
// 我们通过XmlBeanFactory实现类启动Spring IoC容器 
public class Test {
    @org.junit.Test
    public void test(){ 
        //获取配置文件
        ResourcePatternResolver  resolver=new PathMatchingResourcePatternResolver(); 
        Resource rs=resolver.getResource("classpath:bean.xml");

        //加载配置文件并启动IoC容器
        BeanFactory bf=new XmlBeanFactory(rs);

        //从容器中获取Bean对象
        User user=(User) bf.getBean("user");

        user.speak();
    }
}  

XmlBeanFactory configuration files and start loading Spring IoC container, start IoC container through BeanFactory, and will not initialize Bean defined in the configuration file, create initialization action when the first call. In the initialization BeanFactory, must provide a logging framework, we use Log4J.
2.ApplicationContext
  ApplicationContext derived from the BeanFactory provides more features for practical application. In BeanFactory, many functions require programming to achieve, while the ApplicationContext can be achieved by way of configuration. The main classes are implemented ApplicationContext ClassPathXmlApplicationContext and a FileSystemXmlApplicationContext, the former profile is loaded from the default class path, which is the default configuration is loaded from the file system, as follows:

// 和BeanFactory初始化相似,ApplicationContext初始化也很简单
ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");

ApplicationContext BeanFactory initialization and initialize a significant difference, did not initialize Bean BeanFactory initialized when the container is created only when the first visit Bean; while the ApplicationContext instantiation at initialization Bean all single instances. Therefore, ApplicationContext initialization time will be slightly longer.
3.WebApplicationContext
  the WebApplicationContext is prepared specifically for the Web application, which allows Web relative to the root directory of the path loading a configuration file to complete the initialization. Can be obtained from the WebApplicationContext ServletContext references, the entire object is placed in the ServletContext WebApplicationContext as an attribute, to access the Web application environments can Spring application context. ConfigurableWebApplicationContext extends WebApplicationContext, allows configuration example of WebApplicationContext, defines two important ways.

setServletContext(ServletContext servletcontext):为Spring设置ServletContext

setConfigLocation (String [] configLocations): Set Spring configuration file address.

WebApplicationContext initialize the timing and manner are: the use of ContextLoaderListener listener Spring provided to monitor ServletContext object is created, when the ServletContext object is created, the object is created and initialized WebApplicationContext. Therefore, we only need to configure the listener to web.xml.

<!-- 利用Spring提供的ContextLoaderListener监听器去监听ServletContext对象的创建,并初始化WebApplicationContext对象 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Context Configuration locations for Spring XML files(默认查找/WEB-INF/applicationContext.xml) -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

4.BeanFactory, ApplicationContext and WebApplicationContext and differences between
  Spring describe dependencies between Bean and Bean through a configuration file, by reflection technology Java language can instantiate Bean and establish dependencies between Bean. Spring IoC container Upon completion of these low-level work, but also provides a cache bean instances, life-cycle management, event publishing, resource loading and other advanced services.

Spring BeanFactory is the core interface that provides advanced configuration mechanism of IoC. ApplicationContext BeanFactory is based on a sub-interface BeanFactory, providing more application-oriented functions. We generally referred to as the IoC container BeanFactory, ApplicationContext context for the application, also known as the Spring container. WebApplicationContext is designed for Web application ready, which allows Web relative to the root directory of the path loading a configuration file to complete the initialization, is sub-interface ApplicationContext interface.

BeanFactory is the basis of the Spring framework, Spring for itself; ApplicationContext for developers using the Spring framework, almost all of the applications we use directly ApplicationContext BeanFactory instead of the underlying; WebApplicationContext is designed for Web applications.
  The father and son vessel
  through HierarchicalBeanFactory interfaces, Spring IoC container can associate the parent-child hierarchy system: access to child container Bean parent container, the parent container can not be accessed Bean child container.

Spring Sons container implemented using many features, such as Spring MVC controller Bean located subcontainer, service and persistence layers Bean located in the parent container. But even so, the controller can also refer Bean Bean persistence layer and business layer, and service layer and persistence layer will not see the controller Bean.

Guess you like

Origin blog.csdn.net/qq_43378945/article/details/102657414