Spring hello world

What is Spring

Spring is an open source, lightweight Java development framework; it is a core feature can be used to develop any Java application, the goal is to make the Spring framework to develop JavaEE application easier, the core concept is the IOC and AOP; this Spring is also the focus of learning;

Spring is not for a specific function, frame specific level; that is to say before the others system hierarchy, structure, design patterns are not necessary to change , but let Spring join, make development easier ; remember Spring and do not want to replace an existing framework , but allow each with the use of the framework to reduce the difficulty , it's like 502 glue, can quickly integrate other excellent framework in the system

Spring is also named because of its characteristics, meaning the spring JavaEE development come

Why Spring

We often see Spring replace EJB, EJB or Spring and contrast, etc. related articles, then in the end what is the relationship between the two?

Before we know of course, EJB is a JavaEE specification, mainly for the development of distributed applications

From the conceptual point of view:

  • Spring is a box of the aircraft, the framework is to help you achieve a part of the function of semi-finished products
  • The EJB is a specification for specification (guidance) developers how to achieve JavaEE program

So the question is really asking Spring (frame) and JavaEE (specification) of the comparison, but because the two are not the same concept, so are not directly comparable, in contrast to that in the end what can not be guessing?;

The question should be: using Spring in full accordance with the development and application development JavaEE specification differences

This question should be answered by the author of Spring Rod Johnson:

#Rod Johnson在2002年编写的《Expert One-to-One J2EE Design and Development》一书,Rod 在本书中对J2EE正统框架臃肿、低效、脱离现实的种种学院派做法提出了质疑,并以此书为指导思想,编写了interface21框架,也就是后来的Spring。

Indeed Spring launch is the introduction of private developers question the place of the official specification of insufficient raised and made a strong response in the early stages, developers have experienced a hug to abandon, from the earliest after the launch of the official agreement JavaEE, developers are very support, after all, is the official Well, I gradually began to find this pile of complicated, obscure, how bloated the cost of high learning specification is unbearable, just like you hit a bird while out for a fighter; in this when Spring framework came into being, because of its lightweight, easy to use it will soon be everyone's favorite;

Fortunately, the government has also recognized the problem, so in EJB3.0 made a lot of improvements, and Spring draws some very good features, but a flourishing Spring does not seem to be greatly affected, as always, everyone's favorite Spring;

EJB container IOC container

On the other hand because the Spring container with ICO, can help us manage Bean, EJB and the EJB container needs to be put in to use the features it offers; EJB mainly used to provide distributed capabilities, and IOC container is to help us better solution decoupling

Spring's advantages

  • Spring JavaEE of some API (JDBC, JavaMail, remote calls, etc.), provided the package, difficult to reduce the use of these API;
  • One-stop framework that can quickly and easily integrate other frameworks;
  • The IOC, using dependency injection, greatly reducing the coupling between the components and improve the overall scalability;
  • AOP (Aspect Oriented) programming support, the program can easily intercepted permissions, run monitoring;
  • Declarative transaction support, configuration can be completed by the management of the affairs of disorderly conduct manual programming;
  • Containerized, Spring and manage application objects contain the configuration and life cycle, you can configure how each bean is created and bean is a single instance or every time a new instance is generated when needed, and how they are interrelated .

IOC, IN

concept

Inversion of control (Inversion of Control, abbreviated as the IoC ), one design principles of object oriented programming, can be used to reduce the degree of coupling between the computer code.

A portion of the original logic implemented by a program to the system to turn on complete inversion of control is called

The most common method is called dependency injection (Dependency Injection, referred to as the DI ) by inversion of control, it can be said dependency is injected into the subject.

Dependency injection is a means to control inversion;

Why do I need IOC

For example: With their assembly machine, the need to consider the compatibility of the various components and their performance requirements, such as CPU, memory, graphics, and the like; however, the assembly machine with a dedicated server provider (IOC container), as long as you tell him your basic needs, for example, to a chicken computer, the rest is up to service providers to do;

Most applications, there are many different objects cooperate with each other to complete the business logic, which results in getting a partner, must be displayed to a new object, which will lead to code highly coupled and difficult to maintain and debug. Like this

public class Controller {
    @Test
    public void doGet() throws Exception {
        //这里需要依赖Service层
        UserService service = new UserService("参数1","参数2");
    }

When replacement of other business logic class would have to modify the source code, and if needed instantiation parameters Service Controller layer will have to provide for the necessary parameters, which reflects the degree of coupling is high with Service Controller of

Spring Architecture

image-20200104155828158

Core, provides a fundamental part of the frame, including the DI and IoC;

Beans, provides the BeanFactory, to achieve the factory mode, generic objects and obtaining singletons

context, based on core and bean on other libraries can be integrated with Spring

SpEL (spring-expression Language) provides expression language support, its the JSP EL is extended

AOP, provides aspect-oriented programming

Aspects module provides integration with AspectJ is a powerful and mature AOP framework

Instrumentation for monitoring agent running JVM JAVA program, modified to implement the bytecode AOP

Messaging module provides support for the STOMP, mainly from the WebSocket client processing information STOMP

Emphasize:

Spring is modular, can be introduced according to the desired needs module

Getting Started

Traditional writing

A first look at when not in use Spring, control and business logic to interact case, the controller:

public class Controller {

    @Test
    public void doGet() throws Exception {
        //这里需要依赖Service层

        //v1 直接写
        //UserService service = new UserService();

        //v2 面向接口 某个实现类
        //UserService service = new UserServiceImpl();
        //要跟换其他实现类时  违反了OCP(开放封闭)原则
        //UserService service = new UserServiceImpl2();

        //v3 为避免修改源代码扩展 加入工厂
        ServiceFactory factory = new ServiceFactory();
        UserService service = factory.getService();

        //调用业务方法
        service.userLogin("jerry","admin");
    }
}

factory:

public class ServiceFactory {
    public UserService getService() throws Exception {
        //此处id应配置在xml中
        String id = "UserServiceImpl";
        if (id.equals("UserServiceImpl")){
            return new UserServiceImpl();
        }else if(id.equals("UserServiceImpl2")){
            return new UserServiceImpl2();
        }
        throw new Exception("id:"+id + "not register");
    }
}

Using the factory pattern can be further reduced coupling between the components, but there are many components, need a lot of plants in the complete system, so that the program becomes complicated, cumbersome;

Spring itself designed as a large object factory, responsible for managing the system design to all objects, and using the dependency DI processing object, when the object A object B no longer need to create their own, but taken from the Spring

image-20200104162456622

Supplement: OCP

Called the Open Closed Principle is a principle of application development should follow

open: open to extension

close: modifying the source code for the closure

The aim is to extend the existing functionality without modifying the source code

Using Spring

1. Create a Maven project

2. Add dependence

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>5.2.2.RELEASE</version>
</dependency>
<!-- Maven会自动下载所有Spring核心容器和aop的依赖-->

3. Create a configuration file

Typically named: applicationContext.xmlOf course, you can also modify placed resourcesunder

<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--使用bean标签,创建Service对象,并交给容器来管理-->
    <bean id="UserService1" class="com.yyh.serviceimpl.UserServiceImpl"/>
    <bean id="UserService2" class="com.yyh.serviceimpl.UserServiceImpl2"/>
</beans>

Namespace declarations can look to the official website, or look directly in the jar, such as:

image-20200104165525668

4. Obtain a subject in need from the Spring

    @Test
    public void doGetUseSpring() throws Exception {
        //创建应用上下文 指定配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
          //从Spring中获取所需对象
        UserService userService = (UserService)context.getBean("UserService2");
        //调用业务逻辑方法
        userService.userLogin("jerry","admin");
    }

Not difficult to see at this time of Spring is the basic function of an object factory, but this is only the Spring

IOC container

Container can be understood as a place to store objects, of course, not just storage, as well as object management, including - create - destroy - Assembly; this program had to do to the Spring, so it belongs to the IOC, called the IOC container;

There are two interfaces Spring ApplicationContext is a subinterface of BeanFactory. Spring they can be used as a container;

image-20200104180458270

Differences between the two containers:

As BeanFactory mainly for top-level interface to the Spring Framework itself, it provides only the basic functions of a container such as DI

ApplicationContext, is the BeanFactory sub-interfaces, which means more than BeanFactory functionality, such as internationalization, configuration annotations, XML configuration, etc.

Take the lazy way BeanFactory loaded, when acquiring the object will be instantiated

ApplicationContext is initialized at the factory will immediately instantiate an object

ApplicationContext implementation class difference between the two:

  • ClassPath retrieves the configuration file from the classpath

  • FileSystem retrieves the configuration file from the file system

Guess you like

Origin www.cnblogs.com/yangyuanhu/p/12150153.html