StringBoot入门
创建项目
使用的工具是idea
首先:
File–>Moudule
在右边选择Spring Initializr
创建完之后会下载一个压缩包
这个创建好之后他本身就是一个web项目
并且他本身带有tomcat
,每一个springboot都自己带有一个tomcat,不需要使用我们本机的tomcat再去带
然后我们回到idea继续创建
注意这里必须要有网,不然是创建不了的
项目名一定不能有大写
如果有大写的英文字符点下一步之后就会报下面这个错,提醒你项目名有非法字符
正确的写法是下面这种:
其他的暂时先不勾选,暂时还用不到
示例
创建好之后写代码简单测试一下
运行使用springboot自带的tomcat
运行成功!
注意这里不需要加项目名,因为使用的是springboot的自带tomcat
Springboot配置文件
内置属性
注意:实际项目开发的时候Port=80,Context-path=/,以下配置只为讲解相关知识点
改端口,加项目名
测试
但是这样的话当要配置多个的时候就不是很清楚,所以使用下面这种会比较清晰:
将application的后缀改成.yml
然后使用下面这种格式
这样也是一样的效果
自定义属性
属性封装类
定义属性封装类
controller层
结果如下:
代码
helloController
package com.solar.springboot01.Controller;
import com.solar.springboot01.configurationProperties.MysqlEntity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
/**
* @author SHE
* @create 2020-11-27 10:06
* @RestController相当于reponsebody+controller
*/
@RestController
public class HelloController {
@Value("${mysql.driver}")
private String driver;
@Value("${mysql.url}")
private String url;
@Value("${mysql.username}")
private String username;
@Value("${mysql.password}")
private String password;
@Resource
private MysqlEntity mysqlEntity;
@RequestMapping("/mysql1")
public String mysql1(){
return this.driver+"</br>"+this.url+"</br>"+this.username+"</br>"+this.password+"</br>";
}
@RequestMapping("/mysql2")
public MysqlEntity mysql2(){
return this.mysqlEntity;
}
@RequestMapping("/hello1")
public String hello1(){
return "hello springboot!!";
}
@RequestMapping("/say1")
public String say1(String name){
return name + "say hello springboot";
}
@RequestMapping("/say2/{name}")
public String say2(@PathVariable("name") String name){
return name + "say hello springboot";
}
@RequestMapping("/json")
public Map returnJson(){
Map map = new HashMap();
map.put("success",true);
map.put("msg","恭喜你中奖了!!!");
return map;
}
}
MysqlEntity
package com.solar.springboot01.configurationProperties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author SHE
* @create 2020-11-27 11:07
* data可以代替getset方法
*/
@Component
@Data
@ConfigurationProperties(prefix = "mysql")
public class MysqlEntity {
private String driver;
private String url;
private String username;
private String password;
}
application.properties
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=UTF-8
mysql.username=root
mysql.password=
后面添加的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>