SpringBoot学习笔记

SpringBoot是SpringMVC的升级,但两者并未有直接的联系,其中一者可以取代另一者,其中SpringBoot作为下一代框架,有它独特的优势:省去了繁琐了xml配置,为微服务提供了基础(微服务架构的流程一般为SpringBoot–>SpringCloud–>微服务)

这篇学习记录使用的IntelliJ IDEA创建的,是用idea创建springboot项目流程:file–>project–>Spring Initializr–>……
项目位置:idea中的girl

然后习惯使用Eclipse的同学也可以使用Eclipse来创建springboot工程,正常创建流程:
new–>project…–>springboot–>Spring Starter Project,然后设置对应的项目名、包名等等,创建的默认是Maven项目,可以选择其中内置的一些依赖关系。

1.配置文件

项目默认配置文件默认是application.properties,正常配置项目端口以及路径时会加上这两个语句:

server.port=8080
server.context-path=/girl

这样启动项目时就会在8080端口运行,而且项目的访问根目录也会变成/girl,但是这样的配置方式太过繁杂,完全可以用application.yml的配置方式来取代他,这时的配置就变成了:

server:
  context-path: /girl
  port: 8082

注意context-path:和/girl之间必须有一个空格,port:和8082之间也必须有一个空格,配置完成后可以写一个简单的Controller:

package com.hhu.girl;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @RequestMapping(value="/hello",method = RequestMethod.GET)
    public String say() {
        return "Hello Spring-Boot!!!";
    }
}

然后启动该项目:打开启动文件GirlApplication,右击run"GirlApplication",启动成功后,浏览器访问localhost:8082/girl/hello即可看到"Hello Spring-Boot!!!"
同样还可以将配置文件中的属性通过@Value(" y m l 文 件 中 配 置 的 变 量 名 " ) < / f o n t > 注 解 的 方 式 注 入 到 变 量 中 , 比 如 在 配 置 文 件 中 加 上 c u p S i z e 、 a g e 、 c o n t e n t 这 些 属 性 : ∗ ∗ {yml文件中配置的变量名}")</font>注解的方式注入到变量中,比如在配置文件中加上cupSize、age、content这些属性: ** yml")</font>cupSizeagecontent符千万不要丢啊!**这里说明如何注入单个变量以及如何注入复合变量content(注意配置文件中的写法)

server:
  context-path: /girl
  port: 8080
cupSize: B
age: 18
content: "cupSize: ${cupSize},age: ${age}"

那么此时可以通过如下的方式注入到变量中:

package com.hhu.girl;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @Value("${cupSize}")
    public String cupSize;

    @RequestMapping(value="/hello",method = RequestMethod.GET)
    public String say() {
	    System.out.println(cupSize);
        System.out.println(age);
        return content;
    }
}

除此之外,还有一种情况:以对象的方式进行注入,在yml配置文件中,将gril的两个属性统一这样写:

girl:
  cupSize: B
  age: 18

然后就不要单独对某个属性进行赋值了,而是新建一个girl对象,提供getter和setter方法即可,将这个对象交给Spring作为一个bean来管理(可以加上@Component注解,不能掉,否则无法注入对象属性),设置对象在yml配置文件中的前缀@ConfigurationProperties(prefix = “girl”)即可自动匹配对应的属性:

package com.hhu.girl;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "girl")
public class GirlProperties {

    private String cupSize;
    private Integer age;

    public String getCupSize() {
        return cupSize;
    }

    public void setCupSize(String cupSize) {
        this.cupSize = cupSize;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "GirlProperties{" +
                "cupSize='" + cupSize + '\'' +
                ", age=" + age +
                '}';
    }
}

在Controller中注入对象,根据需求来获取属性即可:

package com.hhu.girl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @Autowired
    private GirlProperties girlProperties;

    @RequestMapping(value="/hello",method = RequestMethod.GET)
    public String say() {
        return girlProperties.toString();
    }
}

还有可能不同的环境有不同的配置需求,比如一种情况可能需要cupSize为B的,另一种情况可能需要cupSize为F的,这时候可以创建针对两种情况的配置文件:

//情况1:需要cupSize为B的情况,改配置文件为application-dev.yml
server:
  context-path: /girl
  port: 8081
girl:
  cupSize: B
  age: 18

另一种情况下配置文件为:

//配置文件名为application-pro.yml
server:
  context-path: /girl
  port: 8081
girl:
  cupSize: F
  age: 18

那么在IDE中需要一个总的配置问文件来做一个统一的管理,再来一个application.yml

spring:
  profiles:
    active: prod

这里可以根据不同的需求来更改到底使用application-dev还时application-prod的配置文件,当然这里完全可以用cmd的方式来同时启动两种环境下的配置(java -jar…),因为毕竟端口不一样。

2.Controller的使用

@Controller:处理http请求;
@RestController:Spring4之后新加的请求,原来的返回json需要用@ResponseBody配合@Controller才可以接受,现在就相当与两者的综合体;
@RequestMapping:配置映射路径,正常来说是配置一个路径即可,如:
@RequestMapping(value="hello",method=RequestMethod.GET)
当然如果想将一个页面映射到多个路径的话可以在用大括号来搞定,比如:

@RequestMapping(value={"/hello","/hi"},method=RequestMethod.GET)

@RequestParam:获取请求参数,在url中?后面所带的参数,比如“localhost:8080/girl/hello?name=air”,针对?后面的参数,这个时候方法的参数可以这么写:

public String say(@RequestParam("id") Integer id ) {
	System.out.println(id);
	return id;
}

@PathVariable:获取url中的数据,比如说映射路径写为:“/say/{id}”,针对占位符,传参为

public String say(@PathVariable("id") Integer id) {
	System.out.println(id);
	return id;
}

那么访问时所带的id参数将会在后台打印;

@GetMapping:组合注解

3.数据库操作

Spring-Data-Jpa,其中JPA(Java Persistence API)定义了一系列对象持久化的标准,Spring-Data-Jpa就是Spring对Hibernate的整合,jpa简单到不敢想,因为对数据库的操作利用jpa来实现的话全程不用写一句SQL语句,但与此同此,应该也会带来性能损失。下面看Demo:
pom配置如下:



	4.0.0

	com.hhu
	girl
	0.0.1-SNAPSHOT
	jar

	girl
	Demo project for Spring Boot

	
		org.springframework.boot
		spring-boot-starter-parent
		1.5.7.RELEASE
		 
	

	
		UTF-8
		UTF-8
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-devtools
			runtime
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		

		
			org.springframework.boot
			spring-boot-starter-thymeleaf
		

		
			org.springframework.boot
			spring-boot-starter-data-jpa
		

		
			mysql
			mysql-connector-java
		

	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	




Spring的yml配置文件如下:

spring:
     profiles:
       active: dev
     datasource:
       driver-class-name: com.mysql.jdbc.Driver
       url: jdbc:mysql://localhost:3306/db_studentinfo
       username: root
       password: 921228
     jpa:
       hibernate:
         ddl-auto: update
       show-sql: true

写一个对数据库操作的接口,让其实现JpaRepository接口,一切操作将随之变得简单:

package com.hhu.girl;

import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface GirlRepository extends JpaRepository{
    //通过年龄查询,这是自定义的,其他的普通方法,jpa接口中都已经写好
    public List findByAge(Integer age);
}

再写一个Controller即可,测试过程借用postman,

package com.hhu.girl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class GirlController {

    @Autowired
    private GirlRepository girlRepository;

    @Autowired
    private GirlService girlService;

    /*
        get获取girls列表
     */
    @GetMapping(value="/girls")
    public List getGirls() {
        return girlRepository.findAll();
    }

    /*
    创建一个girl,PostMapping
     */
    @RequestMapping(value = "/girls", method = RequestMethod.POST)
    public Girl creteGirl(@RequestParam("age") Integer age,@RequestParam("cupSize") String cupSize) {
        Girl g = new Girl();
        g.setAge(age);
        g.setCupSize(cupSize);
        girlRepository.save(g);
        return g;
    }

    //查询一个Girl,GetMapping
    @RequestMapping(value = "/girls/{id}", method = RequestMethod.GET)
    public Girl searchGirl(@PathVariable("id") Integer id) {
        return girlRepository.findOne(id);
    }

    //根据年龄查询
    @RequestMapping(value="/girls/age/{age}", method = RequestMethod.GET)
    public List searchByAge(@PathVariable("age") Integer age) {
        return girlRepository.findByAge(age);
    }

    //更新一个Girl,PutMapping
    @RequestMapping(value = "/girls/{id}", method = RequestMethod.PUT)
    public Girl updateGirl(@PathVariable("id") Integer id, @RequestParam("age") Integer age,  @RequestParam("cupSize") String cupSize) {
        Girl g = new Girl();
        g.setId(id);
        g.setAge(age);
        g.setCupSize(cupSize);
        return girlRepository.save(g);
    }

    //删除一个Girl,DeleteMapping
    @RequestMapping(value="/girls/{id}", method = RequestMethod.DELETE)
    public String deleteGirl(@PathVariable("id") Integer id) {
        girlRepository.delete(id);
        return "delete success! ";
    }

    @RequestMapping(value="/girls/insert2")
    public void insert2Girl() {
        girlService.insertTwo();
    }
}

你可能感兴趣的:(#,SpringBoot)