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语句有关。

使用mybatis-XML方式

model

和pojo没什么区别本质都是拿来接受数据库结果

package com.example.people.model; public class PeoModel { private int id; private String dep; private String job; private String name; private String time; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getDep() { return dep; } public void setDep(String dep) { this.dep = dep; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } @Override public String toString() { return "OrderPojo [id=" + id + ", dep=" + dep + ", job=" + job + ", name=" + name + ", time=" + time + "]"; } }

Mapper

java代码部分的Mapper,文件放在和service同级的目录,里面声明了操作数据库的抽象方法

package com.example.people.mapper; import java.util.List; import org.apache.ibatis.annotations.Mapper; import com.example.people.model.PeoModel; @Mapper public interface PeoMapper { List<PeoModel> getAllPeo(); PeoModel getById(int id); }

Mapper(XML配置文件,放在resource/mapper里面,分离sql和Mapper便于管理,命名和java文件夹那边的一致)

  • namespace用来绑定java写的mapper
  • id用来绑定mapper下面的方法
  • #{id}是获取java写的mapper的方法的参数,如果传入的是对象{}包裹的是对象的属性即可
<?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.example.people.mapper.PeoMapper"> <select id="getAllPeo"> select * from people </select> <select id="getById"> select * from people where id = #{id} </select> </mapper>

service

package com.example.people.service; import java.util.List; import com.example.people.model.PeoModel; public interface XmlService { public List<PeoModel> getAllPeo(); public PeoModel getById(int id); }

实现类

package com.example.people.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.people.mapper.PeoMapper; import com.example.people.model.PeoModel; import com.example.people.service.XmlService; @Service public class XmlServiceImpl implements XmlService { @Autowired PeoMapper peoMapper; @Override public List<PeoModel> getAllPeo() { return peoMapper.getAllPeo(); } @Override public PeoModel getById(int id) { return peoMapper.getById(id); } }

controller

package com.example.people.controller; import org.springframework.web.bind.annotation.RestController; import com.example.people.model.PeoModel; import com.example.people.service.XmlService; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; @RestController public class XmlController { @Autowired XmlService xmlService; @GetMapping("xmlAll") public List<PeoModel> xmlAll() { return xmlService.getAllPeo(); } @GetMapping("xmlId") public PeoModel xmlId(@RequestParam int id) { return xmlService.getById(id); } }

运行结果

图1为/getAllPeo,图2为/getById

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