Use springBoot quickly build a web backend engineering

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/Mr__Viking/article/details/89602511

springBoot is a very new technology now java circle of fire, is also another open source project development team spring, now it seems that this project is very popular, so the author also intends to use its own systematic way to learn about this door technology, today to say something about how to use springBoot quickly build a web backend engineering.

When we started using springBoot, we look back to open a project when using SSM what work needs to be done? First we need to create in the IDE in a Maven-based web project, then we need to import spring a bunch of dependencies, then we need to look for spring xml configuration files, but also modify the web.xml file and so on .... this at a number of words will be omitted. Overall, the SSM is also a lot of configuration is very complex, if you previously developed several projects are used by SSM, then you probably already have a mature system configuration, and then open a new project that is the original of a set of configuration copied on the line. But never had time for a complete set of configuration files or need to be upgraded version of the framework, the headache is still very annoying.

So today we learn to use springBoot configure a web project what you need to do.

1. The project quickly generate a springBoot

Spring may be aware of the team, to build from scratch a spring project of various pain, so the design springBoot time to consider more humane. Developers only need to open start.spring.io on it according to their need to choose a suitable configuration, and then generate a good springBoot project download.

As for those who need to choose the configuration, you need only click on the first 5:00 following sell all will be able to see all rely springBoot integration support.

Author chose the web, Jpa, mySql these options to use them to configure a simple start-up projects.

2. Start project

将下载好到本地的压缩包打开,然后让IDE去导入依赖的jar包,完成之后我们启动一个这个项目。

启动的方式不再是先启动tomcat容器了,springBoot内部已经集成了一个tomcat,因此我们无需再做配置,只需要找到src/main/java下面的根目录中的Application.java文件,然后选择运行这个文件即可。

下面我们看一下启动后的样子:

但是我们会发现运行失败了!

错误提示是说我们没有配置数据源的url,所以当我们在springBoot项目中加入JPA依赖后就必须要配置数据源的信息。

好吧,我们把数据源的信息写上

下面再来试试:

启动成功!

3.测试MVC功能

前面写到我们在项目中加入了MVC的web依赖包,下面我们来测试一下MVC的功能。

在application类中编写一个接口:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class MySpringBootApplication {

	@RequestMapping("/")
	public String home(){
		return "SpringBoot Start!欢迎使用";
	}

	public static void main(String[] args) {
		SpringApplication.run(MySpringBootApplication.class,args);
	}

	@RequestMapping("use")
	public String used(String key){
		return "used:"+key;
	}
}

然后我们启动后访问一下http:localhost:8080/   看下运行结果:

这里有一点需要注意,在springBoot的项目中,它已经默认为我们配置了编码方式为UTF-8,因此我们的中文没有出现乱码。

从这里可以看出springBoot的优势了,我们若要新建web工程只需要在配置中加入一个web依赖,一切都不需要再配置了,在SSM中我们还要配置请求转发器、过滤器和跨域等等...你只需要照着已经配置好的springMVC的功能使用就行了。

跨域配置,在通常的项目开发中我们都选择的是前后端分离模式,因此跨域是必不可少的,下面我们就来配置一下springBoot的跨域支持。

新建一个配置类或者在一个已有的配置类中添加一个方法:

package com.viking.MySpringBoot.config.mvc;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Created by Viking on 2019/4/26
 * 匿名内部类实现跨域配置
 */
@Configuration
public class MyConfiguration {

    @Bean
    public WebMvcConfigurer crossConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}

 This will configure a cross-domain. This configuration is to write an anonymous inner class inside the method, the same we can also be configured by another way, inheritance WebMvcConfigurer interfaces, and override void addCorsMappings (CorsRegistry registry) method can, because in WebMvcConfigurer All interface methods are added to the default keyword modifications in the interface they already have their own method body, so we do not have to implement all of its methods when we inherit the interface.

Implement WebMvcConfigurer interface configuration mode:

package com.viking.MySpringBoot.config.mvc;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Created by Viking on 2019/5/6
 * 重写接口方法实现配置跨域
 */
@Configuration
@EnableWebMvc
public class CORSConfiguration implements WebMvcConfigurer {

    public void addCorsMappings(CorsRegistry registry) {
        //设置允许跨域的路径
        registry.addMapping("/**")
                //设置允许跨域请求的域名
                .allowedOrigins("*")
                //这里:是否允许证书 不再默认开启
                .allowCredentials(true)
                //设置允许的方法
                .allowedMethods("*")
                //跨域允许时间
                .maxAge(3600);
    }
}

 They can choose one of two or more, can achieve cross-domain requests.

4. Test JPA

When springBoot MyBatis can be supported, but the authors believe that since it is springBoot great esteem function, then we have to try anything different places.

In the previous configuration file, I wonder if you have not noticed, I will mysql data source driver configured to comment, why not configuration-driven database connection can use? Because springBoot described in the document, it may be automatically determined in what needs to be driven by the data source url. But you have to add the drive depends on the job in the pom file.

Also note that it is, it must be developed using the time zone database in the url when using JPA data source, otherwise it will fail.

Write the following paragraph JPA test code:

Entity Weather.java

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Date;

/**
 * Created by Viking on 2019/4/27
 * 测试springBoot中jpa的url参数
 */
@Entity(name = "weather")
public class Weather {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long rid;
    private String weather;
    private float temperature;
    private String tip;
    private Date date;

    public long getRid() {
        return rid;
    }

    public void setRid(long rid) {
        this.rid = rid;
    }

    public String getWeather() {
        return weather;
    }

    public void setWeather(String weather) {
        this.weather = weather;
    }

    public float getTemperature() {
        return temperature;
    }

    public void setTemperature(float temperature) {
        this.temperature = temperature;
    }

    public String getTip() {
        return tip;
    }

    public void setTip(String tip) {
        this.tip = tip;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}

Repository Interface WeatherRepository.java:
 

import com.viking.springboot.MySpringBoot.pojo.Weather;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * Created by Viking on 2019/4/27
 */
public interface WeatherRepository extends JpaRepository<Weather,Long> {
}

Test categories:


import com.viking.springboot.MySpringBoot.dao.WeatherRepository;
import com.viking.springboot.MySpringBoot.pojo.Weather;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Date;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MySpringBootApplicationTests {
	@Autowired
	private WeatherRepository weatherRepository;

	@Test
	public void contextLoads() {
		Weather weather = new Weather();
		weather.setWeather("冰雹");
		weather.setTemperature(10.0f);
		weather.setTip("冰雹天气,请注意预防自然灾害");
		weather.setDate(new Date());
		weatherRepository.save(weather);
	}

}

Observation Database Results:

                                     

Insert the test is successful, try again query:

package com.viking.springboot.MySpringBoot;

import com.viking.springboot.MySpringBoot.dao.WeatherRepository;
import com.viking.springboot.MySpringBoot.pojo.Weather;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Date;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MySpringBootApplicationTests {
	@Autowired
	private WeatherRepository weatherRepository;

	@Test
	public void contextLoads() {
		Weather weather = new Weather();
		weather.setWeather("冰雹");
		weather.setTemperature(10.0f);
		weather.setTip("冰雹天气,请注意预防自然灾害");
		weather.setDate(new Date());
		weatherRepository.save(weather);
	}

	@Test
	public void testQuery(){
		Page<Weather> page = weatherRepository.findAll(PageRequest.of(0, 2));
		System.out.println("list:"+page.getContent());
		System.out.println("total:"+page.getTotalElements());
	}

}

JPA query comes with support for paging, as we no longer need to use in MyBatis as in pagination plugin.

Look at the results:

testing successfully!

To summarize: in general, the use of springBoot quickly build a web project is not a problem, but SpringBoot very user-friendly design, the use of springBoot is a trend in the future, and there are a lot of configuration did not introduce complete, the authors also to seriously to learn springBoot, again one study in a future article.

 

Guess you like

Origin blog.csdn.net/Mr__Viking/article/details/89602511