Spring Boot 笔记

目录

0.建立SpringBoot工程

1.SpringBoot工程全局变量设置

2.SpringBoot工程初始化函数

3.不同类之间的引用

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

5.Vue编译到SpringBoot工程的jar包

6.线程池的代码样例

7. http协议通信

8.使用mybatis


工作中能复用的技巧和代码,提高工作效率,成就美好人生!

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;
    }
}

5.Vue编译到SpringBoot工程的jar包

 使用build命令编译vue工程,将生成的dist文件夹内的static文件夹和index.html文件拷贝到springboot工程的static文件夹下:


6.线程池的代码样例

import java.util.concurrent.*;

class ThreadPoolTest {
    public void cachedThreadPool() {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        for(int i=0;i<10;i++) {
            threadPool.execute(()->{
                while(true){
                    System.out.println(Thread.currentThread().getId());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    public void fixedThreadPool() {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        for(int i=0;i<10;i++) {
            int finalI = i;
            threadPool.execute(()->{
                int count = 5;
                while(true){
                    System.out.println(Thread.currentThread().getId() + ":" + finalI);
                    if(0 == --count) {
                        break;
                    }

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    public void scheduledThreadPool() {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        scheduledExecutorService.scheduleAtFixedRate(()->{
            System.out.println(Thread.currentThread().getId() + ":one second pass");
        }, 0, 1, TimeUnit.SECONDS);
    }
}


public class Main {
    public static void main(String[] args) {
        ThreadPoolTest threadPoolTest = new ThreadPoolTest();
        threadPoolTest.scheduledThreadPool();
    }
}

7. http协议通信

import net.sf.json.JSONObject;
        import org.springframework.http.ResponseEntity;
        import org.springframework.web.client.RestTemplate;

public class http_test {

    public JSONObject httpGet(){
        RestTemplate rt = new RestTemplate();
        String urlGet = "http://localhost:8886/Test/get";
        ResponseEntity<JSONObject> response = rt.getForEntity(urlGet, JSONObject.class);
        JSONObject body = response.getBody();
        return body;
    }

    public JSONObject httpPost() {
        JSONObject jobj = new JSONObject();
        jobj.element("name","caoyi").element("password","123");
        RestTemplate rt = new RestTemplate();
        String urlGet = "http://localhost:8886/Test/set";
        ResponseEntity<JSONObject> response = rt.postForEntity(urlGet, jobj, JSONObject.class);
        JSONObject body = response.getBody();
        return body;
    }

    public static void main(){

    }
}

8.使用mybatis

package com.cet34.cap.mapper;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface MysqlMapper {
    @Update("CREATE TABLE all_data (\n" +
            "`id` INT(32) NOT NULL AUTO_INCREMENT COMMENT '主键',\n" +
            "`srcIp` VARCHAR(20) DEFAULT NULL COMMENT '源IP',\n" +
            "`dstIp` VARCHAR(20) DEFAULT NULL COMMENT '目的IP',\n" +
            "`srcPort` VARCHAR(10) DEFAULT NULL COMMENT '源端口',\n" +
            "`dstPort` VARCHAR(10) DEFAULT NULL COMMENT '目的端口',\n" +
            "`protocol` VARCHAR(10) DEFAULT NULL COMMENT '协议',\n" +
            "`data` LONGTEXT DEFAULT NULL COMMENT '数据包内容',\n" +
            "`time` VARCHAR(20) DEFAULT NULL COMMENT '数据包时间',\n" +
            "PRIMARY KEY (`id`)\n" +
            ") ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin")
    void createTable();

    @Select("SELECT COUNT(*) FROM information_schema.TABLES WHERE table_name ='#{tableName}'")
    List<JSONObject> isExist(String tableName);

    @Select("SELECT * FROM all_data")
    List<JSONObject> selectAll();

    @Select("SELECT * FROM all_data WHERE ${key} = #{value}")
    List<JSONObject> select(String key, String value);

    @Insert("INSERT INTO all_data VALUES (NULL,#{srcIp},#{dstIp},#{srcPort},#{dstPort},#{protocol},#{data},#{time})")
    void insertData(String srcIp, String dstIp, String srcPort, String dstPort, String protocol, String data, String time);

    @Update("UPDATE all_data set ${key}=#{value} where id = #{id}")
    void updateData(String key, String value, int id);

    @Delete("DELETE FROM all_data where id = #{id}")
    void deleteData(int id);
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值