Spring learning - [getting started] - getting started with spring

Getting started with Spring

Article directory

Summary

Spring is the most popular enterprise Java application development framework. Millions of developers from all over the world use spring framework to create good performance, easy to test and reusable code.

The Spring framework is an open source Java platform, which was originally written by Rod Johnson and first released under the Apache 2.0 license in June 2003.

Spring is a lightweight framework with a base version of only about 2 MB.

The core feature of Spring framework is that it can be used to develop any Java application, but it needs to be extended to build web application on Java EE platform. The goal of the Spring framework is to make J2EE development easier to use and to promote good programming practices by enabling POJO based programming models.

Benefits of using Spring framework

Here are the main benefits of using the Spring framework:

  • Spring enables developers to use POJOs to develop enterprise applications. The advantage of using POJOs only is that you don't need an EJB container product, such as an application server, but you can choose to use a robust servlet container, such as Tomcat or some commercial products.
  • Spring is organized in a unit pattern. Even if the number of packages and classes is very large, you just have to worry about what you need, and the rest can be ignored.
  • Spring won't let you waste your time doing repetitive work. It really takes advantage of some existing technologies, such as ORM framework, log framework, JEE, Quartz and JDK timer, and other view technologies.
  • It's easy to test an application written in Spring because environment related code is moved into the framework. In addition, by using JavaBean style POJOs, it becomes easier to inject test data using dependency injection.
  • Spring's web framework is a well-designed web MVC framework, which provides a good alternative for such as structures or other engineering or less popular web frameworks. The MVC pattern separates different aspects of the application (input logic, business logic, and UI logic) while providing loose coupling between these elements.
    • The model encapsulates the application data, which usually consists of POJO classes.
    • View is responsible for rendering model data. Generally speaking, it generates HTML output that can be interpreted by client browser.
    • The controller is responsible for handling user requests and building the appropriate model and passing it to the view for rendering.
  • Spring provides encapsulation for some APIs (JDBC, JavaMail, remote call, etc.) that are very difficult to use in Java EE development, which greatly reduces the application difficulty of these APIs.
  • Lightweight IOC containers are often lightweight, for example, when compared to EJB containers. This facilitates the development and deployment of applications on computers with limited memory and CPU resources.
  • Spring provides a consistent transaction management interface that extends down to (using a single database, for example) local transactions and to global transactions (using JTA, for example).

hello spring

1.1 jdk environment configuration

slightly

1.2 install IDE

The mainstream java ide can support the development of spring, such as eclipse intellij netbean vscode sts, etc. Here we choose intellij for development

1.3 prepare maven environment

maven is an essential tool for java programming. It can help developers build complex java applications quickly through simple scripts and commands. It can help developers manage dependency, test, package, compile, accompany with continuous integration tools, and maven can also help developers realize automatic deployment of projects.

The integrated ide such as eclipse and intellij have maven tools built in by default, but in the actual development process, it is still recommended that you install maven by yourself and specify the path to manage the local maven library

To install maven:

1. Download maven application

Here we download the Maven binary file directly: http://mirror.bit.edu.cn/apache/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.zip

2. Unzip the zip package and configure the environment variables

Configure Maven? Home

[failed to transfer the pictures in the external link. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-MSGaXjwz-1580978657923)(image/mvn1.PNG))

Add the maven command set to the system environment variable

[failed to transfer the pictures in the external link. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-cTLAcYxk-1580978657924)(image/mvn2.PNG))

Open command line, test

mvn -v
------------
Maven home: D:\software\apache-maven-3.6.3\bin\..
Java version: 1.8.0_45, vendor: Oracle Corporation, runtime: C:\Program Files\java\jdk1.8.0_45\jre
Default locale: zh_CN, platform encoding: GBK
OS name: "windows 8.1", version: "6.3", arch: "amd64", family: "windows"

3. Configure maven environment in intellij (see 1.4)

4. Configure the Alibaba cloud image of the maven central warehouse

The default central warehouse of maven is not stable in China. It is recommended to map the central warehouse to Alibaba cloud image

Modify the maven installation directory / conf/settings.xml file and add the following to its label

<mirrors>
    <mirror>
        <id>alimaven</id>
        <name>aliyun maven</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
        <mirrorOf>central</mirrorOf>       
    </mirror>
</mirrors>

5. Configure maven local warehouse address

maven will save the jar package downloaded from the Central Library under the user directory by default, that is, the local warehouse. If you want to modify the warehouse address, add the following configuration in settings.xml

<localRepository>d:\mvnRepo</localRepository>

1.4 creating a hello world project

1. intellij creates maven project

[external link image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-O5TQ1CRH-1580978657926)(image / create project 1.PNG)] specify the directory where the project is located and the project name (note that the project path does not have Chinese, and it is better not to use the first level subdirectory under the drive letter)

[failed to transfer the pictures in the external link. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-ezf1SQEW-1580978657926)(image / creation project 2.PNG))

2. Configure automatic import of maven project

intellij supports real-time monitoring of rule changes in maven projects and automatic import of dependent packages

When we first open the project, we will find that the following dialog box pops up in the lower right corner of intellij. Please select enable auto import

[failed to transfer the pictures in the external link. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-vLd1MRg6-1580978657927)(image/auto import.PNG))

If there is no pop-up or selection, please open maven settings and check auto import

[failed to transfer the pictures in the external chain. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-nvzrjqv-1580978657928) (image / MVN auto import 2.png))

3. Configure intellij maven

Because intellij has maven api, it uses maven and default local warehouse address by default. Here we need to set the maven api that we download manually and use secondary configuration when we create other projects. Therefore, we need to set the maven configuration of new projects as well as the maven configuration of this project

Configure current project

[failed to transfer the pictures in the external link. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-8aQoJrKQ-1580978657930)(image / configuration mvn1.png))

[external link picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-LgrQkHXN-1580978657931)(image/mvn configuration 2.png))

Global project configuration

The global project configuration is the same as the current project configuration, except that the options are in other settings

[external link image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-KURCMeNz-1580978657931)(image / global setting mvn.png))

4 project directory structure

After the project is created, its directory structure is as follows

[failed to transfer the pictures in the external link. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-8ksouqds-1580978657932) (image / project directory structure. png))

pom.xml is the core configuration file of maven project, which defines the maven construction rules of this project

1.5 write the first spring application

1. Import project dependency

Firstly, the minimal dependency of spring framework is introduced into pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.3.RELEASE</version>
    </dependency>
</dependencies>

If automatic import is configured at this time, intellij will automatically download the dependency package. After the first successful download, if the next maven project uses the dependency package, it will be imported directly from this warehouse

After downloading, we can see that intellij displays the following dependencies under external libraries

[failed to save the image in the external link. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-dLDvRbYd-1580978657934)(image/hello spring project depends on. png))

2. Write code

Create the following classes

entity bean
package com.neusoft.model;

public class Good {

    public Good() {
    }

    public Good(String goodName, Double price, Long goodId) {
        this.goodName = goodName;
        this.price = price;
        this.goodId = goodId;
    }

    private String goodName;
    private Double price;
    private Long goodId;

    public String getGoodName() {
        return goodName;
    }

    public void setGoodName(String goodName) {
        this.goodName = goodName;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public Long getGoodId() {
        return goodId;
    }

    public void setGoodId(Long goodId) {
        this.goodId = goodId;
    }
}

dao and implementation class
package com.neusoft.dao;

import com.neusoft.model.Good;

public interface GoodDao {

    Good findGoodById(Long id);
}

package com.neusoft.dao;

import com.neusoft.model.Good;

public class GoodDaoImpl implements GoodDao {

    public Good findGoodById(Long id) {
        if(id==1L){
            return new Good("Soap",12.8, 1L);
        }else if (id==2L){
            return  new Good("Mask",22.8, 2L);
        }else if (id==3L){
            return  new Good("84 disinfectant",42.8, 3L);
        }
        return null;
    }
}

service and implementation class
package com.neusoft.service;

import com.neusoft.model.Good;

public interface GoodService {

    Good findGoodById(Long id);
}

package com.neusoft.service;

import com.neusoft.dao.GoodDao;
import com.neusoft.model.Good;

public class GoodServiceImpl implements GoodService {
    private GoodDao goodDao;

    public Good findGoodById(Long id) {
        return goodDao.findGoodById(id);
    }

    public void setGoodDao(GoodDao goodDao) {
        this.goodDao = goodDao;
    }
}

3. Assemble the spring container

1. xml assembly

xml is the oldest container assembly method in spring. Its advantage is that it can make our code completely decoupled from spring and keep the code pure. However, with the change of spring ecological environment status, this method is not used very frequently

Write spring-ctx01.xml in the resource directory

<?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="goodDao" class="com.neusoft.dao.GoodDaoImpl"/>

    <bean id="goodService" class="com.neusoft.service.GoodServiceImpl" >
        <property name="goodDao" ref="goodDao"/>
    </bean>
</beans>

Create program main entry

package com.neusoft;

import com.neusoft.model.Good;
import com.neusoft.service.GoodService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloSpring {

    public static void main(String[] args) {
        //Create the IOC container and specify the profile address: spring-ctx01.xml under classpath
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-ctx01.xml");

        //Get GoodService according to id or name. This method needs strong conversion
        GoodService goodService = (GoodService) context.getBean("goodService");

        //Call query method
        Good good = goodService.findGoodById(1L);

        if(good!=null){
            System.out.printf("good name is %s, good price is %f,good id is %d",good.getGoodName(),good.getPrice(),good.getGoodId());
        }

    }
}

Run tests:

good name is Soap, good price is 12.800000,good id is 1
Process finished with exit code 0
2. java config mode

With the distributed process of Internet application, the core idea of spring has changed from simply realizing decoupling through dependency injection to adapting to the idea of agile development. Therefore, the need of decoupling is not as strong as before, and the high efficiency of development is more concerned by spring. Therefore, the great power of spring lies in the extensive use of annotations and the subsequent dynamic initialization configuration , all of which are based on java config

Create the main configuration class AppConfig

package com.neusoft.config;

import com.neusoft.dao.GoodDao;
import com.neusoft.dao.GoodDaoImpl;
import com.neusoft.service.GoodService;
import com.neusoft.service.GoodServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    @Bean
    public GoodDao goodDao(){
        return new GoodDaoImpl();
    }

    @Bean
    public GoodService goodService(){
        GoodServiceImpl goodService = new GoodServiceImpl();
        goodService.setGoodDao(goodDao());
        return goodService;
    }
}

Create main program entry

package com.neusoft;

import com.neusoft.config.AppConfig;
import com.neusoft.model.Good;
import com.neusoft.service.GoodService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloSpring2 {

    public static void main(String[] args) {
        //Create the IOC container and specify the profile address: spring-ctx01.xml under classpath
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

        //Get GoodService according to id or name. This method needs strong conversion
        GoodService goodService = (GoodService) context.getBean("goodService");

        //Call query method
        Good good = goodService.findGoodById(1L);

        if(good!=null){
            System.out.printf("good name is %s, good price is %f,good id is %d",good.getGoodName(),good.getPrice(),good.getGoodId());
        }

    }
}

Run tests:

good name is Soap, good price is 12.800000,good id is 1
Process finished with exit code 0

2. Spring integration Junit test

In addition to using the main function to test spring, we need more detailed unit testing tools to test different modules in a really complex application scenario. Here we use the spring test package with junit to test

First, junit and spring test dependencies are introduced into pom.xml

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.3.RELEASE</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

Write a test class in the test folder

package com.neusoft;

import com.neusoft.config.AppConfig;
import com.neusoft.model.Good;
import com.neusoft.service.GoodService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:spring-ctx01.xml")
@ContextConfiguration(classes = AppConfig.class)
public class SpringTest1 {
    @Autowired
    private GoodService goodService;
    
    @Test
    public void test1(){
        Good good = goodService.findGoodById(2L);
        System.out.println(good);
    }
}

Execute test method, result

...
com.neusoft.model.Good@1fa268de
Process finished with exit code 0
234 original articles published, 2.55 praised, 290000 visitors+
Private letter follow

Tags: Spring Maven xml Java

Posted on Thu, 06 Feb 2020 04:13:51 -0500 by Adika