springboot入门
LYT
首页
分类
标签
项目
留言
友链
关于

springboot入门

2023年12月14日14时16分
2023年12月14日14时19分
java
java springboot maven
浏览量:
总浏览量:
0

springboot环境搭建

配置环境

  • jdk17+
  • maven 打开环境变量里面把java和maven目录下的bin文件路径添加到path里面

idea配置

推荐下载idea专业版(社区版也是可以开发springboot的)。安装完成以后需要进行下面配置。

使用idea专业版创建springboot项目,Server Url换成下面

https://start.aliyun.com

完成以上操作以后就可以正式开发springboot了。

入门案例

XXXApplication是入口类,在它同级目录下,新建一个hello文件夹,新建一个HelloController类并写入以下程序。

package com.lyt11.spring1.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping("/lyt") public String Hello(){ return "hello world"; } }

读取配置文件

配置文件介绍

springboot的配置文件有两种,properies和yml格式,推荐用yml格式,可读性强,在resource文件夹下新建application.yml,里面可以修改一些默认配置比如端口,还可以自定义一些配置项。

# 配置端口 server: port: 2121 # 自定义配置项 lyt: name: "李亚泰" age: 24 score: 92

读取配置文件的方法

准备工作

首先在启动类的同级目录下(注意这里是要新建一个bean,位置必须在启动类的同一个包下,不然扫描不到bean),新建一个目录,这里命名为utils,然后写一个类

package com.lyt11.spring1.utils; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; @Component public class MemberConfig { public String name; public int age; public int score; @Override public String toString() { return "MemberConfig{" + "name='" + name + '\'' + ", age=" + age + ", score=" + score + '}'; } } controller类调用 ```java package com.lyt11.spring1.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.lyt11.spring1.utils.MemberConfig; @RestController public class HelloController { @Autowired MemberConfig memberConfig; @RequestMapping("/lyt") public String Hello(){ return memberConfig.toString(); } }

@Value方式读取

使用@Value注解方式读取配置文件,需要为每一个属性进行注解。

package com.lyt11.spring1.utils; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; @Component public class MemberConfig { @Value("${lyt.name}") public String name; @Value("${lyt.age}") public int age; @Value("${lyt.score}") public int score; @Override public String toString() { return "MemberConfig{" + "name='" + name + '\'' + ", age=" + age + ", score=" + score + '}'; } }

@ConfigurationProperties方式获取

@ConfigurationProperties通过设置前缀来获取配置文件的信息,@ConfigurationProperties(prefix = "xxx")

package com.lyt11.spring1.utils; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; @ConfigurationProperties(prefix = "lyt") @Component public class MemberConfig { public String name; public int age; public int score; public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public void setScore(int score) { this.score = score; } @Override public String toString() { return "MemberConfig{" + "name='" + name + '\'' + ", age=" + age + ", score=" + score + '}'; } }

springboot整合mybatis

引入maven坐标

需要引入mabatis和数据库驱动包。

<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-spring-boot3-starter --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-spring-boot3-starter</artifactId> <version>3.5.5</version> </dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>8.1.0</version> </dependency>

配置文件

在配置文件application.yml里面编写数据库相关信息。

spring: datasource: url: jdbc:mysql://localhost:3306/your_database_name?useSSL=false&serverTimezone=UTC username: your_username password: your_password driver-class-name: com.mysql.cj.jdbc.Driver

使用mybatis例子

比如我们要查询数据库cash表里面的信息。注意接下来的每个步骤新建的包都要在启动类的同一包下,不然springboot扫描不到相应的bean。具体的数据库表和pojo对象可以自行修改。

pojo

java类模型,用来接收数据库传回来的数据,在启动类同一个包下新建pojo包,然后新建一个Cash对象。

package com.lyt11.springbootmybaits.pojo; public class Cash { private int money; private String type; private String date; public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } }

Mapper

定义了与数据库进行交互的SQL语句的方法。这些方法通常对应于特定的SQL语句,如查询、插入、更新或删除等操作。新建一个mapper包,新建一个CashMapper接口

package com.lyt11.springbootmybaits.mapper; import com.lyt11.springbootmybaits.pojo.Cash; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; @Mapper public interface CashMapper { @Select("select * from book where date =${date}") public Cash findByDate(String date); }

Service

Service包即业务层,主要负责处理应用程序的业务逻辑。新建一个service包,然后在这个包下新建一个CashService接口

package com.lyt11.springbootmybaits.service; import com.lyt11.springbootmybaits.pojo.Cash; import org.apache.ibatis.annotations.Select; public interface CashService { public Cash findByDate(String date); }

再在这个包下新建一个子包impl存放实现类,新建一个CashServiceImpl类来实现CashService接口。

package com.lyt11.springbootmybaits.service.impl; import com.lyt11.springbootmybaits.mapper.CashMapper; import com.lyt11.springbootmybaits.pojo.Cash; import com.lyt11.springbootmybaits.service.CashService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class CashServiceImpl implements CashService { @Autowired private CashMapper mapper; @Override public Cash findByDate(String date) { return mapper.findByDate(date); } }

controller

最后新建controller包,在controller包下新建一个CashController包来调用CashServiceImpl

package com.lyt11.springbootmybaits.controller; import com.lyt11.springbootmybaits.pojo.Cash; import com.lyt11.springbootmybaits.service.CashService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class CashController { @Autowired private CashService cashService; @RequestMapping("/findByDate") public Cash findByDate(String date){ return cashService.findByDate(date); } }

运行结果

访问localhost:8080/findByDate?date=%222023-11-26%2013:34:29%22,注意这个链接跟你的sql语句有关。

bean注册

注解方法

| 注解 | 说明 | 位置 | | ----------- | -------------------- | ------------------------------------------------- | | @Component | 声明bean的注解 | 不属于以下三类 | | @Controller | @Component的衍生注解 | 标注在控制器上 | | @service | @Component的衍生注解 | 标注在业务类上 | | @Repository | @Component的衍生注解 | 标注在数据访问类上(由于与mybatis整合用的比较少) |

如果要注册bean对象来自第三方,无法用@component

注册第三方bean

@Bean

@Bean是Spring框架中的一个注解,用于在@Configuration类中声明bean。通过@Bean注解,我们可以手动定义和配置bean,并将其注册到Spring容器中。

  • 使用@Bean注解来声明一个bean的方法,可以具有以下几个特征:

  • 方法的名称默认将作为bean的名称,除非通过name属性指定其他名称。

  • 方法通常返回一个对象实例,该对象将成为Spring容器中的bean。

  • Spring框架会自动管理通过@Bean注解声明的bean,包括其生命周期和依赖注入。

  • 可以通过initMethod和destroyMethod属性指定bean的初始化和销毁方法,用于在bean的生命周期不同阶段执行一些逻辑操作。

  • 可以使用@Scope注解指定bean的作用域(singleton、prototype、request、session等)。

写配置文件

在启动类下面新建一个config文件夹,然后创建一个CommonConfig.java文件

package com.lyt11.springboot3register.config; import cn.itcast.pojo.Country; import cn.itcast.pojo.Province; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class CommonConfig { // 创建Bean @Bean public Country country(){ return new Country(); } // 默认名字是方法名 // 如果方法的内部需要使用到ioc容器中已经存在的bean对象,那么只需要在方法上声明即可,spring会自动的注入 @Bean("squire") public Province province(Country country){ System.out.println(country.toString()); return new Province(); } }

获取Bean

在启动类里面获取Bean并打印出来

@SpringBootApplication public class Springboot3RegisterApplication { public static void main(String[] args) { ApplicationContext context = SpringApplication.run(Springboot3RegisterApplication.class, args); Country country = context.getBean(Country.class); System.out.println(country); Province province = (Province) context.getBean("squire"); System.out.println(province); } }

@import

当配置类所在的路径不在启动类的同一文件夹下,这个时候就需要使用@import,此外还需要用到ImportSelector来管理需要使用的配置类。

  • 将config文件夹移动到启动类同一文件夹外。
  • 自定义一个CommonConfigSelector类并实现ImportSelector接口
  • 在重写接口的方法后,在方法里返回字符串数组,数组中就是配置类的引用
package config; import org.springframework.context.annotation.ImportSelector; import org.springframework.core.type.AnnotationMetadata; public class CommonConfigSelector implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { // 返回所需要的配置类 return new String[]{ "config.CommonConfig" }; } }

注册条件

SpringBoot提供了设置注册生效条件的注解@Conditional

| 注解 | 说明 | | ------------------------- | ---------------------------------------- | | @ConditionalOnProperty | 配置文件中存在对应属性,才声明该bean | | @ConditionalOnMissingBean | 当不存在当前类型bean时,才声明该bean | | @ConditionalOnClass | 当前环境存在指定的这个类时,才声明该bean |