1.第一个程序
环境配置,需要下载 Maven ,框架生成后
在 src/main/java/自定义应用名中写入
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@GetMapping("/test")
public Object test() {
return "hello world";
}
}
默认端口为8080
浏览器访问 127.0.0.1:8080/test 即可看到返回内容
SprintBoot 可以不依赖xml文件运行
2.系统注解
@SpringBootApplication
这是一个启动类
@EnableAutoConfiguration
启动自动配置
根据不同功能引入不同依赖、
在 resources/application.yml文件中写入数据库配置
采用层级输入,每一行比上一行多两格缩进
注意:文件名称不能改变
在 properties文件中也可以写入配置,同级 properties 文件内容优先
resources/config/文件 优先级最高
3.常用的业务逻辑注解
@RestController 配置在主开关文件
@RequestMapping("xxx") 后跟配置项目的主 url ,为避免重复书写
@GetMapping("xxx") get方法访问的接口 url, 一个接口一个url;
路由参数为id时,{id},方法使用 @PathVariable
@PostMapping("xxx") post方法访问的接口
@DeleteMapping("xxx") delete方法访问的接口
@PutMapping("xxx") put方法访问的接口
4.实用操作
自定义User类
import lombok.Data;
@Data 注解,避免写get() set()方法
public class User {
String name;
String sex;
Integer age;
public User(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
构造方法
}
}
主文件调用
@RestController
@SpringBootApplication
@RequestMapping("rest")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@GetMapping("get")
public User get() {
return new User("lilin",11,"男");
}
}
Postman返回
{
"name": "lilin",
"sex": "男",
"age": 11
}
5.Post请求实操
@PostMapping
public User adduser(User user) {
return user;
}
其他请求类似
一般 自定义Service层写业务逻辑
6.部分总结
@Controller 返回的是页面
@RestController 返回的是输出结果
@RestController = @Controller + @ResponseBody
@Service 在接口的实现类上面加 实现Bean的注册
@Autowird 将对象定义为私有对象上面加 获取Bean
如 @Autowird
private 实现类名称/接口名称 user; 省去了一次 new 对象步骤
@component Controller层的注册Bean
@Resource 获取Bean 和 @Autowird的区别
当有多个实现类而对象需要是接口类型
使用 @Resource(name="user" 实现类的首字符小写名称) 来调用
@Resource = @Qualifier + @Autowird
7.最终总结
@value 从配置文件中取值 写法
@value ("${变量名}")
private String 变量名;
@Configuration + @Bean 人为注册Bean