首页 > 其他分享 >springboot基础

springboot基础

时间:2024-06-14 23:43:33浏览次数:29  
标签:springboot boot 基础 springframework org println import public

springboot基础

1. 快速入门

https://docs.spring.io/spring-boot/docs/

https://docs.spring.io/spring-boot/docs/2.1.10.RELEASE/reference/html

https://developer.aliyun.com/mirror/mave

image

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.itheima</groupId>
    <artifactId>springboot-helloworld</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- Inherit defaults from Spring Boot -->
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

</project>
package com.itheima.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String hello(){
        return "hello springboot";
    }
}

package com.itheima;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HelloApplication {
    public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class,args);
    }
}

2. 配置文件

image

image

3. 读取配置文件

image

image

image

package com.itheima.springbootinit;

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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {


    @Value("${name}")
    private String name;

    @Value("${person.name}")
    private String name2;

    @Value("${person.age}")
    private int age;


    @Value("${address[0]}")
    private String address1;

    @Value("${msg1}")
    private String msg1;

    @Value("${msg2}")
    private String msg2;


    @Autowired
    private Environment env;

    @Autowired
    private Person person;


    @RequestMapping("/hello2")
    public String hello2() {

        System.out.println(name);
        System.out.println(name2);
        System.out.println(age);
        System.out.println(address1);
        System.out.println(msg1);
        System.out.println(msg2);

        System.out.println("----------------------");

        System.out.println(env.getProperty("person.name"));
        System.out.println(env.getProperty("address[0]"));

        System.out.println("-------------------");

        System.out.println(person);
        String[] address = person.getAddress();
        for (String s : address) {
            System.out.println(s);
        }

        return "hello Spring Boot 222!";
    }


    @RequestMapping("/hello")
    public String hello() {
        return "hello Spring Boot 222!";
    }
}

@ConfigurationProperties(prefix = "person")
@Component
@Data
public class Person {
    private String name;
    private int age;
}
person:
    name: abc
    age: 20
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
package com.itheima.springbootinit;


@RestController
public class HelloController {
    @Autowired
    private Person person;

    @RequestMapping("/hello2")
    public String hello2() {

        System.out.println(person);
        String[] address = person.getAddress();
        for (String s : address) {
            System.out.println(s);
        }
        return "hello Spring Boot 222!";
    }
}

4. profile

image

image

5. 内部配置加载顺序

image

注意:resource路径下为第4个

6. 整合junit

image

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
package com.itheima.springbootjunit;

import org.springframework.stereotype.Service;

@Service
public class UserService {

    public void show(){
        System.out.println("show....");
    }
}
package com.itheima.test;


import com.itheima.springbootjunit.SpringbootJunitApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * 测试类
 */

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootJunitApplication.class )
public class UserServiceTest {

    @Test
    public void test(){
        System.out.println(111);
    }
}

7.整合mybatis

image

CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci */;

USE `springboot`;

/*Table structure for table `t_user` */

DROP TABLE IF EXISTS `t_user`;

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `password` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

/*Data for the table `t_user` */

insert  into `t_user`(`id`,`username`,`password`) values (1,'zhangsan','123'),(2,'lisi','234');
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.itheima</groupId>
    <artifactId>springboot-mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-mybatis</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <!--<scope>runtime</scope>-->
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

# datasource
spring:
  datasource:
    url: jdbc:mysql:///springboot?serverTimezone=UTC
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

# mybatis
mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml # mapper映射文件路径
  type-aliases-package: com.itheima.springbootmybatis.domain

  # config-location:  # 指定mybatis的核心配置文件
package com.itheima.springbootmybatis.mapper;

import com.itheima.springbootmybatis.domain.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface UserMapper {

    @Select("select * from t_user")
    public List<User> findAll();
}
package com.itheima.springbootmybatis.mapper;

import com.itheima.springbootmybatis.domain.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface UserXmlMapper {
    public List<User> findAll();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.springbootmybatis.mapper.UserXmlMapper">
    <select id="findAll" resultType="user">
        select * from t_user
    </select>
</mapper>
package com.itheima.springbootmybatis;

import com.itheima.springbootmybatis.domain.User;
import com.itheima.springbootmybatis.mapper.UserMapper;
import com.itheima.springbootmybatis.mapper.UserXmlMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootMybatisApplicationTests {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserXmlMapper userXmlMapper;

    @Test
    public void testFindAll() {
        List<User> list = userMapper.findAll();
        System.out.println(list);
    }
    @Test
    public void testFindAll2() {
        List<User> list = userXmlMapper.findAll();
        System.out.println(list);
    }
}

8. 两步实现定时任务

8.1 添加注解@EnableScheduling

@SpringBootApplication
@EnableScheduling
public class springbootApplicationMybatis {

    public static void main(String[] args) {
        SpringApplication.run(springbootApplicationMybatis.class,args);
    }
}

8.2 方法上添加注解@Scheduled()

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@SpringBootApplication
@EnableScheduling
public class springbootApplicationMybatis {

    public static void main(String[] args) {
        SpringApplication.run(springbootApplicationMybatis.class,args);
    }

    //1min 执行一次
    @Scheduled(fixedRate = 1*60*1000)
    public void play(){
        System.out.println("hello sheduled");
    }
    
    //9-22点之间每隔30分钟提醒一次
    @Scheduled(cron = "0 0/30 9-22 * * ?")
    public void play2(){
        System.out.println("hello sheduled");
    }
}

在线生成cron表达式https://cron.qqe2.com/

image

注意:spring只支持前6个,不支持年

image

image
image

9. 异步实现定时任务

image

9.1 开启注解@EnableAsync

package com.itheima;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@SpringBootApplication
@EnableScheduling
@EnableAsync
public class springbootApplicationMybatis {

    public static void main(String[] args) {
        SpringApplication.run(springbootApplicationMybatis.class,args);
    }

    //1min 执行一次
    @Scheduled(fixedRate = 1*60*1000)
    public void play(){
        System.out.println("hello sheduled");
    }
}

9.2 设置异步执行@Async

package com.itheima;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@SpringBootApplication
@EnableScheduling
@EnableAsync
public class springbootApplicationMybatis {

    public static void main(String[] args) {
        SpringApplication.run(springbootApplicationMybatis.class,args);
    }

    //1min 执行一次
    @Async
    @Scheduled(fixedRate = 1000)
    public void play(){
        try {
            Thread.sleep(2*1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("线程名称:"+Thread.currentThread().getName());
        System.out.println("hello sheduled");
    }

    //9-22点之间每隔半小时提醒一次
    @Async
    @Scheduled(cron = "0 0/30 9-22 * * ?")
    public void play2(){
        System.out.println("hello sheduled");
    }
}

10. 整合redis

10.1 本地redis服务

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

启动本地redis服务

package com.itheima;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.data.redis.core.RedisTemplate;

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloApplicationTest {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void set(){
        redisTemplate.boundValueOps("name").set("zhangsan");
    }

    @Test
    public void get(){
        Object name = redisTemplate.boundValueOps("name").get();
        System.out.println(name);
    }
}

10.2 非本地redis服务

server:
  port: 8081
  
spring:
  redis:
    host: 127.0.0.1
    port: 6379

其余与上述代码一致

标签:springboot,boot,基础,springframework,org,println,import,public
From: https://www.cnblogs.com/xinmomoyan/p/18248847

相关文章

  • boost-Asio 基础学习1.5--域名主机名解析筛选resolver
    在开发过程中往往看见的不是ipv4或者ipv6,而是主机的域名!如www.badiu.com而上期文章也说了......
  • 基于SpringBoot+Vue+uniapp微信小程序的垃圾分类系统的详细设计和实现(源码+lw+部署文
    文章目录前言详细视频演示项目运行截图技术框架后端采用SpringBoot框架前端框架Vue可行性分析系统测试系统测试的目的系统功能测试数据库表设计代码参考数据库脚本为什么选择我?获取源码前言......
  • 基于SpringBoot+Vue的学生心理压力咨询评判管理系统(源码+lw+部署文档+讲解等)
    文章目录前言详细视频演示项目运行截图技术框架后端采用SpringBoot框架前端框架Vue可行性分析系统测试系统测试的目的系统功能测试数据库表设计代码参考数据库脚本为什么选择我?获取源码前言......
  • 基于SpringBoot+Vue协同过滤算法的私人诊所管理系统(源码+lw+部署文档+讲解等)
    文章目录前言详细视频演示项目运行截图技术框架后端采用SpringBoot框架前端框架Vue可行性分析系统测试系统测试的目的系统功能测试数据库表设计代码参考数据库脚本为什么选择我?获取源码前言......
  • c++_0基础_讲解4 变量定义
    变量C++中的变量是存储数据值的容器,这些值可以在程序执行过程中被修改和使用。在C++中,变量必须先声明后使用,声明变量也可以称之为定义变量,它告诉编译器在何处以及如何去分配存储空间。接下来我将对C++中的变量定义进行详细的介绍。在C++中,变量的定义由以下几个部分组......
  • c++_0基础_讲解5 判断语句
    判断语句C++是一种计算机编程语言,其提供了多种判断语句来控制程序的执行流程。判断语句允许程序根据条件判断的结果来选择不同的执行路径。在C++中,常用的判断语句有if语句、switch语句和三元运算符。if语句是最常用的判断语句之一。它的基本形式是if(条件表达式){执行语句},其中......
  • springboot+vue+mybatis基于java的物资综合管理系统的设计与实现+PPT+论文+讲解+售后
    如今社会上各行各业,都喜欢用自己行业的专属软件工作,互联网发展到这个时候,人们已经发现离不开了互联网。新技术的产生,往往能解决一些老技术的弊端问题。因为传统物资综合管理系统信息管理难度大,容错率低,管理人员处理数据费工费时,所以专门为解决这个难题开发了一个物资综合管理系......
  • hbase的架构和基础命令
    理解HBaseHBase概述Hbase是一个高可靠性、高性能、面向列、可伸缩的分布式存储系统,用于存储海量的结构化或半结构化,非结构化的数据(底层是字节数组做存储的)HBase处理数据虽然Hadoop是一个高容错、高延时的分布式文件系统和高并发的批处理系统,但是它不适用于提供实时计算;H......
  • Java数据结构:从基础到高级应用
    Java是一种广泛应用的编程语言,拥有强大的数据结构库,使程序员能够轻松地处理各种数据和算法。本文将深入探讨Java中的数据结构,从基础概念到高级应用,包括示例代码和实际用例。第一部分:基础数据结构1.数组(Array)Java中的数组是一种基本的数据结构,用于存储一组相同类型的元素。......
  • python基础
    1.安装问题直接在小黑屏上运行python的界面不友好,可以输入命令:pipinstallipython-ihttps://pypi.douban.com/simple在启动我们的ipython就可以啦安装过程出现的问题:Couldnotfindaversionthatsatisfiestherequirementipython(fromversions:none)ERROR:No......