0
点赞
收藏
分享

微信扫一扫

Spring Boot 笔记一

工程与房产肖律师 2022-04-14 阅读 66
java

0.建立SpringBoot工程

跑通一篇博客代码假装自己会Spring Boot


1.SpringBoot工程全局变量设置

打开工程路径src/main/resources/application.properties文件,定义变量 gVal = helloWorld。在类中通过如下方式引用。

    @Value("${gVal}")
    private String val;

2.SpringBoot工程初始化函数

可以通过重写 ApplicationListener 类,也可以用定时器。

@Service
@EnableScheduling
public class InitService implements ApplicationListener<ContextRefreshedEvent> {

    private String time;
    public String getTime(){
        return time;
    }

    //SpringBoot初始化服务
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println(" init service running! ");
    }

    //定时器
    @Scheduled(cron = "*/1 * * * * ?")
    public void updateTime(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        time = simpleDateFormat.format(new Date());
    }
}

3.不同类之间的引用

在其他服务类引用 InitService 类。

    @Autowired
    InitService initService;

4.API接口定义,不同方式传递参数

@RestController
@CrossOrigin
public class Api {

    @Autowired
    InitService initService;

    @Value("${gVal}")
    private String val;

    //输入 http://localhost:8080/get/val?s=123
    //输出 helloWorld 123
    @GetMapping("/get/val")
    public String getVal(@RequestParam String s) {
        return val + " " + s;
    }

    //输入 http://localhost:8080/get/json 在Postman添加Body: {"name":"peter","sex":1}
    //输出 {"sex": 1,"name": "peter","time": "2022-04-12 21:24:46"}
    @GetMapping("/get/json")
    public JSONObject getJson(@RequestBody JSONObject json) {
        json.put("time", initService.getTime());
        return json;
    }
}
举报

相关推荐

0 条评论