技术面试时的你是否会有这样的感受:
面试官问的好多技术我都用到了,但面试官的问题我们时却不能给出准确的答案。
我们平常在项目中主要关注使用,程序run起来就ok了,很少去了解原理、架构、和性能调优。这样在面试问题中总有一种无法直击问题本质的无力感,很难充分表现自己,最终影响面试结果。
其实,这是很多Java研发人员遇到的普遍问题,不清楚原理,虽然用起来没问题,但讲起来有困难!
为了避免此类问题,本文针对面试中涉及到的Spring Boot核心知识点进行了总结,帮助大家查漏补缺,在技术面试中能够一路通关!
图书推荐
本文选自《Offer来了:Java面试核心知识点精讲(框架篇)》一书,本书将Java分布式架构中常用的技术做了梳理和总结,可谓一书在手,Offer我有!(参与文末互动,有机会赢取本书!)
文章略长但干货足,建议大家先收藏~
本文目录
1. Spring Boot的使用
2. Spring Boot Application Starters
3. Spring Boot的常用组件及其使用
▊ Spring Boot的特点如下
(1)快速创建独立的Spring应用程序。
(2)嵌入Tomcat和Undertow等Web容器,实现快速部署。
(3)自动配置JAR包依赖和版本控制,简化Maven配置。
(4)自动装配Spring实例,不需要XML配置。
(5)提供诸如性能指标、健康检查、外部配置等线上监控和配置功能。
01
Spring Boot的使用
Spring Boot把传统的Spring项目从繁杂的XML配置中解放出来,应用只需要用注解自动扫描即可,同时Spring Boot为应用提供了统一的JAR管理和维护,不需要应用程序管理复杂的JAR依赖和处理多版本冲突问题,只需要在pom.xml文件中加入对应模块的Starter即可。对内部的JAR依赖的管理,Spring Boot会自动维护。具体使用过程如下。
(1)Spring Boot的引入。
Spring Boot项目定义简单,使用方便,第一步需要在pom.xml文件中引入org.springframework.boot及相关依赖。pom.xml文件如下。
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.alex</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>
(2)配置文件设置。
Spring Boot的配置分为application.properties和application.yml两种,两种配置有语法差别,但其实现的功能相同。下面的配置文件通过server.port=9090设置了服务端口为9090,如果不设置,则默认端口为Tomcat的8080,通过server.name=hello设置了服务名称为hello。
server.port=9090 #服务端口号
server.name=hello #服务名称
server.tomcat.uri-encoding=UTF-8 #以Tomcat为Web容器时的字符编码为UTF-8
#spring.data.mongodb.uri=mongodb://localhost:27017/mydb #MongoDB连接地址定义
#spring.http.encoding.charset=UTF-8 #HTTP请求的字符编码为UTF-8
#spring.http.multipart.max-file-size=10MB #设置文件上传时单个文件的大小限制
#spring.http.multipart.max-request-size=100MB #设置文件上传时总文件的大小限制
#spring.mvc.static-path-pattern=/** #设置静态资源的请求路径
#spring.resources.static-locations=classpath:/static/,classpath:/public/
#设置静态资源的路径,多个用逗号隔开
# MySQL数据库配置
#hibernate.dialect=org.hibernate.dialect.MySQL5Dialect #设置数据库方言为MySQL
#hibernate.show_sql=true #设置是否显示SQL语句
#hibernate.hbm2dll.auto=update #设置使用Hibernate的自动建表
#entitymanager.packagesToScan=com.zslin #设置自动扫描的包路径
#spring.datasource.url=jdbc:mysql://localhost:3306/customer?\
#useUnicode=true&characterEncoding=utf-8&useSSL=true&autoReconnect=true
#设置MySQL数据库连接
#spring.datasource.username=root #设置数据库用户名
#spring.datasource.password=123 #设置数据库root用户对应的密码
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver #设置数据库驱动名称
(3)定义启动类。
启动类是Spring Boot项目的入口,应用程序通过在类上设置一个@SpringBootApplication注解,声明该类是一个Spring Boot启动类,Spring Boot会扫描启动类所在的包及其子包中的所有类的注解,并将其加载到Spring Boot的容器中进行管理。只需要在main()函数中执行SpringApplication.run(SpringbootApplication.class, args),便完成了启动类的定义。代码如下。
@SpringBootApplication
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
在定义启动类后,单击右键执行run,便可启动该Spring Boot项目了。
(4)定义控制器
在SpringbootApplication的根目录下定义一个控制器,用于Web接口的访问。控制器的定义方式和在Spring项目中控制器的常规定义方式一样,具体代码如下。
@RestController
public class BaseController {
@RequestMapping("/hello")
public String home() {
return "Hello World!";
}
}
(5)项目启动和访问
在SpringbootApplication上单击右键执行run,便可启动该Spring Boot服务;在浏览器地址栏中输入127.0.0.1:9090/hello,便能访问定义好的REST服务。运行结果如下。
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.4.RELEASE)
......
: Tomcat initialized with port(s): 9090 (http)
: Starting service [Tomcat]
: Starting Servlet engine: [Apache Tomcat/9.0.17]
: Tomcat started on port(s): 9090 (http) with context path ''
: Started SpringbootApplication in 1.671 seconds (JVM running for 2.154)
......
02
Spring Boot Application Starters
Starters是一组资源依赖描述,用于为不同的Spring Boot应用提供一站式服务,而不必像传统的Spring项目那样,需要开发人员处理服务和服务之间的复杂依赖关系。例如,如果要使用Spring的JPA功能进行数据库访问,只需要应用程序在项目中加入spring-boot-starter-data-jpa依赖即可,具体的依赖细节由Starters统一处理,不需要应用程序分别处理各个JAR包的依赖关系。常用的Starters下如表所示。
(点击图片查看大图)
03
Spring Boot的常用组件及其使用
Spring Boot的核心特点是通过Starter能快速将各个组件集成到应用中,并提供良好的操作接口。下面将简单介绍常用组件的使用。
1. Spring Boot使用MySQL
Spring Boot基于Starter能够快速将不同的服务组件集成到应用程序中。Spring Boot服务组件的集成过程分为引入Starter、设置application.properties和使用服务组件(组件会根据配置文件自动装配)3步。MySQL的具体使用如下。
(1)引入Starter。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
(2)设置application.properties。
spring.datasource.url=jdbc:mysql://localhost/test#数据库地址
spring.datasource.username=dbuser#数据库用户名
spring.datasource.password=dbpass#数据库密码
spring.datasource.driver-class-name=com.mysql.jdbc.Driver#数据库驱动
(3)使用服务组件。
@Component
public class MyBean {
private final JdbcTemplate jdbcTemplate;
@Autowired
public MyBean(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
2. Spring Boot使用Redis
(1)引入Starter。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
(2)设置application.properties。
#Redis数据库名称(默认为0)
spring.redis.database=0
#Redis数据库地址
spring.redis.host=172.31.19.222
#Redis数据库端口
spring.redis.port=6379
#Redis数据库密码(默认为空)
spring.redis.password=
#Redis连接池的最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
#Redis连接池的最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
#Redis连接池中的最大空闲连接
spring.redis.pool.max-idle=8
#Redis连接池中的最小空闲连接
spring.redis.pool.min-idle=0
(3)使用服务组件。
@Component
public class MyBean {
private StringRedisTemplate template;
@Autowired
public MyBean(StringRedisTemplate template) {
this.template = template;
}
}
3. Spring Boot使用MongoDB
(1)引入Starter。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId> spring-boot-starter-data-mongodb</artifactId>
</dependency>
(2)设置application.properties。
spring.data.mongodb.uri=mongodb://user:secret@mongo1.example.com:12345,mongo
2.example.com:23456/test
#数据库的连接地址
(3)使用服务组件。
@Component
public class MyBean {
private MongoTemplate template;
@Autowired
public MyBean(MongoTemplate template) {
this.template = template;
}
}
4. Spring Boot使用Neo4j
(1)引入Starter。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId> spring-boot-starter-data-neo4j</artifactId>
</dependency>
(2)设置application.properties。
spring.data.neo4j.uri=bolt://my-server:7687 #Neo4j图数据库地址
spring.data.neo4j.username=neo4j #Neo4j图数据库用户名
spring.data.neo4j.password=secret #Neo4j图数据库密码
(3)使用服务组件。
@Component
public class MyBean {
private final Session session;
@Autowired
public MyBean(Session session) {
this.session = session;
}
}
5. Spring Boot使用Solr
(1)引入Starter。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId> spring-boot-starter-data-solr</artifactId>
</dependency>
(2)设置application.properties。
#Solr数据库地址
spring.data.solr.host: http://127.0.0.1:8080/solr/ciri_core
(3)使用服务组件。
@Component
public class MyBean {
private SolrClient solr;
@Autowired
public MyBean(SolrClient solr) {
this.solr = solr;
}
}
6. Spring Boot使用ElasticSearch
(1)引入Starter。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId> spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
(2)设置application.properties。
#ElasticSearch数据库地址
spring.data.elasticsearch.cluster-nodes=localhost:9300
(3)使用服务组件。
@Component
public class MyBean {
private final ElasticsearchTemplate template;
public MyBean(ElasticsearchTemplate template) {
this.template = template;
}
}
7. Spring Boot使用Cassandra
(1)引入Starter。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId> spring-boot-starter-data-cassandra</artifactId>
</dependency>
(2)设置application.properties。
#Cassandra的命名空间
spring.data.cassandra.keyspace-name=mykeyspace
#Cassandra数据库地址
spring.data.cassandra.contact-points=cassandrahost1,cassandrahost2
(3)使用服务组件。
@Component
public class MyBean {
private CassandraTemplate template;
@Autowired
public MyBean(CassandraTemplate template) {
this.template = template;
}
}
8. Spring Boot使用RabbitMQ
(1)引入Starter。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId> spring-boot-starter-rabbitmq </artifactId>
</dependency>
(2)设置application.properties。
spring.rabbitmq.host=localhost #RabbitMQ服务地址
spring.rabbitmq.port=5672 #RabbitMQ端口号
spring.rabbitmq.username=admin #RabbitMQ用户名
spring.rabbitmq.password=secret #RabbitMQ密码
(3)定义服务组件。
@Component
public class MyBean {
private final AmqpAdmin amqpAdmin;
private final AmqpTemplate amqpTemplate;
@Autowired
public MyBean(AmqpAdmin amqpAdmin, AmqpTemplate amqpTemplate) {
this.amqpAdmin = amqpAdmin;
this.amqpTemplate = amqpTemplate;
}
}
(4)定义队列。
@Configuration
public class QueueConf {
//1:定义Queue实例对象,队列名称为someQueue
@Bean(name="message")
public Queue queueMessage() {
return new Queue("someQueue");
}
}
(5)发送消息。
@Component
public class MyBeanSender {
@Autowired
private AmqpTemplate template;
public void send() {
//向队列someQueue发送一条消息hello,rabbit
template.convertAndSend("someQueue","hello,rabbit");
}
}
(6)接收消息。
@Component
public class MyBean {
//监听和接收队列someQueue上的消息
@RabbitListener(queues = "someQueue")
public void processMessage(String content) {
}
}
9. Spring Boot使用Kafka
(1)引入Starter。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId> spring-boot-starter-kafka </artifactId>
</dependency>
(2)设置application.properties。
#Kafka服务地址
spring.kafka.bootstrap-servers=localhost:9092
#Kafka消费组
spring.kafka.consumer.group-id=myGroup
(3)发送消息。
@Component
public class MyBean {
private final KafkaTemplate kafkaTemplate;
@Autowired
public MyBean(KafkaTemplate kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
public Response sendKafka() {
//向Kafka的someTopic发送一条消息
kafkaTemplate.send("someTopic", "key", message);
}
}
(4)接收消息。
@Component
public class MyBean {
//监听并接收someTopic上的消息
@KafkaListener(topics = "someTopic")
public void processMessage(String content) {
System.out.println("message:"+ content);
}
}
—— 完——
本文分享自 博文视点Broadview 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有