springBoot简单入门

来源:互联网 发布:加加林死亡 知乎 编辑:程序博客网 时间:2024/06/11 23:20

环境准备

1、一个称手的文本编辑器(例如Vim、Emacs、Sublime Text)或者IDE(Eclipse、Idea Intellij)
2、Java环境(JDK 1.7或以上版本)
3、Maven 3.0+(Eclipse和Idea IntelliJ内置,如果使用IDE并且不使用命令行工具可以不安装)

生成springBoot框架的web项目

idea可以自动生成
地址:http://start.spring.io/

启动项目(3种)

1、代码运行
2、命令:项目下 mvn spring-boot:run
3、先编译 java install
cd target
java -jar 项目名-0.0.1-SNAPSHOT.jar

application.yml文件的编写

application.properties改成application.yml。

1、application.yml中

```    cupSize: B```

java中获取

```@Value("${cupSize}")    private String cupSize;```

2、application.yml中配置参数中有配置参数

 cupSize: B age: 18 content: "cupSize: ${cupSize},age: ${age}"

3、application.yml中对象

```girl: cupSize: B age: 18```

java中可以创建一个对象接受配置参数

```@Component@ConfigurationProperties(prefix="girl")public class GirlParam {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;}

}
“`

4、引用其他application-dev.yml文件

spring:  profiles:    active: dev

Controller的使用

@Controller 处理http请求
@RestController spring4之后新加的注解,原来返回json格式需要@ResponseBody和配合@Controller

1、Controller返回模板

pom.xml需加入

        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-thymeleaf</artifactId>            <scope>模板</scope>        </dependency>

模板放在这个文件夹下。此方法不怎么推荐,因为现在的开发基本是前后端分离。
这里写图片描述

数据库操作

需要spring-data-jpa ,JPA(Java Persistence API)定义了一系列对象持久化的标准,目前实现这一规范的产品有Hibernate,TopLinkD等。
我用的是mysql的数据库。

pom.xml需加入

<dependency>                                <groupId> org.springframework.boot</groupId>    <artifactId>spring-boot-starter-data-jpa</artifactId>    <scope>data-jpa</scope></dependency><dependency>    <groupId>mysql</groupId>    <artifactId>mysql-connector-java</artifactId>    <scope>mysql</scope></dependency>

application.yml需加入

spring:    datasource:        driver-class-name: com.mysql.jdbc.Driver        url: jdbc:mysql://127.0.0.1:3306/test        username: root        password: root    jpa:       hibernate:         ddl-auto: update       show-sql: true

新建一个类(数据库字段)

对象类必须要一个无参构造方法。

package com.yj.entity;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;@Entity//对应数据库的一个public class Girl {    @Id    @GeneratedValue//自增的    private Integer id;    private String cupSize;    private Integer age;    public Girl() {    }    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    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;    }}
原创粉丝点击