使用springBoot快速搭建一个web后端工程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Mr__Viking/article/details/89602511

springBoot是现在java圈内非常火的一个新技术,同样是spring团队开发的另一个开源项目,目前看来这个项目是非常受欢迎的,所以作者也打算用自己的方式系统性的学习一下这门技术,今天就来讲讲怎样使用springBoot快速搭建一个web后端工程。

在我们开始使用springBoot时,我们回顾一下使用SSM时开启一个项目需要做哪些工作?首先我们需要在IDE中新建一个基于Maven的web工程,接着我们需要导入spring的一堆依赖包,然后我们需要去找spring的xml配置文件,还要修改web.xml文件等等....此处省略若干字。总体来说就是SSM的配置就很多也很杂,如果你之前开发的几个项目都是使用的SSM,那么你多半已经有一套成熟的配置体系了,再开启一个新项目也就是把原来的一套配置复制过来就行了。但对于没有过一套完整的配置文件或者需要对框架的版本进行升级时,这个头痛的问题依然是很讨厌的。

因此我们今天来学习使用springBoot配置一个web工程需要做哪些操作。

1.快速生成一个springBoot项目

可能是spring团队意识到了,从零开始搭建一个spring项目的各种痛楚,所以在设计springBoot的时候考虑的更加人性化了。开发者只需要打开start.spring.io就可以了根据自己的需要选一个合适的配置,然后将一个生成好的springBoot项目下载下来。

至于要选那些需要的配置,只需要你点击第5点下面的sell all就可以了看到springBoot支持的所有的整合依赖。

作者选的是web、Jpa、mySql这几个选项,先用他们来配置一个简易的启动项目。

2.启动项目

将下载好到本地的压缩包打开,然后让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("/**");
            }
        };
    }
}

 这样就配置好跨域了。这种配置方法是写了一个匿名的内部类在方法里面了,同样的我们还可以通过另外一种方式来配置,继承WebMvcConfigurer接口,并重写void addCorsMappings(CorsRegistry registry)方法即可,因为在WebMvcConfigurer接口中所有的方法都加了default关键字修饰,在接口中它们已经有了自己的方法体,所以我们继承该接口时不用必须实现其所有方法。

实现WebMvcConfigurer接口配置方式:

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);
    }
}

 以上两种任选其一即可,都能实现跨域请求。

4.测试JPA

在springBoot中时可以支持MyBatis的,但是作者认为既然是springBoot大力推崇的功能,那么我们就试试看有什么不同的地方。

在前面的配置文件中不知你有没有注意到,我将数据源的mysql驱动配置给注释了,为什么不配置数据库连接的驱动就能使用?因为在springBoot在文档中介绍了,它可以通过数据源的url地址来自动判断需要用哪种驱动。但是你必须要在pom文件中添加驱动的依赖才行。

另外需要注意一点的是,使用JPA时在数据源的url中必须制定数据库使用的时区,否则会运行失败。

下面编写一段JPA的测试代码:

实体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接口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> {
}

测试类:


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);
	}

}

观察数据库结果:

                                     

插入操作测试成功,再来试试查询:

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的查询自带支持分页,再也不需要我们像在MyBatis中那样去使用分页插件了。

看看运行结果:

测试成功!

总结一下:总体来说使用springBoot快速构建一个web工程是没有问题的,而且SpringBoot的设计非常地人性化的,使用springBoot是未来的一个趋势,后面还有很多的配置并没有介绍完整,所以作者也要认真地去学好springBoot,在以后的文章再一一学习。

猜你喜欢

转载自blog.csdn.net/Mr__Viking/article/details/89602511