SSM学习11:springboot基础
教学视频
黑马程序员SpringBoot3+Vue3全套视频教程,springboot+vue企业级全栈开发从基础、实战到面试一套通关
springboot基础
搭建项目
修改配置文件
修改application.yml
(后缀名不对,可以改成这个),配置数据库
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTCusername: rootpassword: 123abc
运行
配置文件
书写
# 普通属性
email:host: smtp.qq.comusername: 123456789@qq.compassword: 123456# 数组
hobbies:- 1- 2- 3- 4
- 值前边必须用空格,作为分隔符
- 使用空格作为缩进表示层级关系,相同的层级左侧对齐
获取值
1、使用@Value("${键名}")
@Component
public class EmailProperties {public String getHost() {return host;}public void setHost(String host) {this.host = host;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Value("${email.host}")private String host;@Value("${email.username}")private String username;@Value("${email.password}")private String password;
}
@Controller
public class HelloController {@AutowiredEmailProperties emailProperties;@RequestMapping("/hello")@ResponseBodypublic String hello() {return emailProperties.getHost();}
}
2、在类上使用ConfigurationProperties
@Component
@ConfigurationProperties(prefix = "email")
public class EmailProperties {public String getHost() {return host;}public void setHost(String host) {this.host = host;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}private String host;private String username;private String password;
}
其他不变
bean管理
Bean扫描
在springboot
项目的启动类中使用了@SpringBootApplication
,这个注解是@SpringBootConfiguration
、@EnableAutoConfiguration
和@ComponentScan
三个注解的组合。
@SpringBootApplication
默认会对应用主类所在包及其子包进行扫描,寻找带有@Component
、@Service
、@Repository
和@Controller
等注解的类,并将它们注册为Spring
容器中的Bean
。
注意:
默认会加载启动类所在包及其子包进行扫描,包之外的可以在启动类上使用注解:@ComponentScan(basePackages = {"org.example"})
进行配置
bean注册
@Component
,声明注解,不属于以下三类时,使用@Controller
,@Component
的衍生注解,标注在控制器类上@Service
,@Component
的衍生注解,标注在业务类上@Repository
,@Component
的衍生注解,标注在数据访问类上(由于与mybatis
整合,用的少)