LYT

推荐下载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注解方式读取配置文件,需要为每一个属性进行注解。
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(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 + '}'; } }
需要引入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
比如我们要查询数据库cash表里面的信息。注意接下来的每个步骤新建的包都要在启动类的同一包下,不然springboot扫描不到相应的bean。具体的数据库表和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; } }
定义了与数据库进行交互的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包,然后在这个包下新建一个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包下新建一个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语句有关。

和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 + "]"; } }
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文件夹那边的一致)
<?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>
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); } }
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


| 注解 | 说明 | 位置 |
|---|---|---|
| @Component | 声明bean的注解 | 不属于以下三类 |
| @Controller | @Component的衍生注解 | 标注在控制器上 |
| @service | @Component的衍生注解 | 标注在业务类上 |
| @Repository | @Component的衍生注解 | 标注在数据访问类上(由于与mybatis整合用的比较少) |
如果要注册bean对象来自第三方,无法用@component
@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并打印出来
@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,此外还需要用到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 |