1.入门案例
1.创建项目
也可以在官网创建springboot项目
2.新建一个controller类
package com.yrh.controller;
@RestController
@RequestMapping("/books")
public class BookController {
@GetMapping("/{id}")
public String getById(Integer id){
System.out.println("id = "+id);
return "hello spring boot";
}
}
3.运行
然后运行Springboot01demoApplication类,在postman中测试连接,服务器正确的收到了id,并返回字符串,说明springboot程序成功执行
2.springboot的配置
1.修改端口号:
也可以将此处的ym扩展名改为yaml
配置文件优先级:peopertiex > yml > yaml
以后做配置主要在yml中配置
2.读取yml中的数据
用Environment读取数据(注意自动装配):
package com.yrh.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/books")
public class BookController {
@Value("${lesson}")
private String lesson;
@Value("${enterprise.subject[0]}")
private String subject00;
@Autowired
private Environment environment;
@GetMapping("/{id}")
public String getById(Integer id) {
//System.out.println("id is " + id);
System.out.println(lesson);
System.out.println(environment.getProperty("lesson"));
System.out.println(environment.getProperty("enterprise.subject[0]"));
return "hello wang wei";
}
}
3.通过Enterprise类读取数据(常用)
1.定义Enterprise类
@Component
@ConfigurationProperties(prefix = "enterprise")
public class Enterprise {
private String name;
private int age;
public String tel;
public String[] subject;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String[] getSubject() {
return subject;
}
public void setSubject(String[] subject) {
this.subject = subject;
}
@Override
public String toString() {
return "Enterprise{" +
"name='" + name + '\'' +
", age=" + age +
", tel='" + tel + '\'' +
", subject=" + Arrays.toString(subject) +
'}';
}
}
2.自动装配
@RestController
@RequestMapping("/books")
public class BookController {
@Value("${lesson}")
private String lesson;
@Value("${enterprise.subject[0]}")
private String subject00;
@Autowired
private Enterprise enterprise;
@GetMapping("/{id}")
public String getById(Integer id) {
//System.out.println("id is " + id);
System.out.println(enterprise);
return "hello wang wei";
}
}
3.springboot整合Mybatis
事先定义好Account实体类,和数据库表account
@Mapper
public interface AccountDao {
@Select("select * from account where id = #{id}")
public Account getById(int i);
}
在测试类中调用getById
@SpringBootTest
class Springboot01demoApplicationTests {
@Autowired
private AccountDao account;
@Test
void contextLoads() {
Account account1 = account.getById(1);
System.out.println(account1);
}
}