一、Spring Boot簡介
Spring Boot是Spring框架的後續版本,簡化了Spring的配置,讓使用Spring更加方便快捷。使用Spring Boot可以實現快速構建企業級應用程序,並且優化了開發體驗和開發效率。Spring Boot使用了約定優於配置的方式,即默認情況下防止合理的默認配置,開發者只需要在必要時進行配置,不需要進行複雜的配置,大大提升了開發效率。
二、Spring Boot常見面試題
1. Spring Boot有哪些優點?
Spring Boot的優點主要有:
(1)簡化配置:使用Spring Boot可以減少Spring框架的配置代碼量,不再需要繁瑣的配置XML。
(2)自動配置:Spring Boot自動根據項目的依賴關係和默認規則,自動配置Bean和環境。
(3)快速開發:Spring Boot提供諸多開箱即用的解決方案,比如模板引擎、數據訪問、安全控制等,可以極大地提高開發效率。
(4)服務監測:Spring Boot可以自動監測應用程序中的服務和組件,保證應用程序的準確性和穩定性。
2. 如何在Spring Boot中使用AOP?
// 首先定義需要攔截的註解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Loggable {
}
// 定義切面
@Aspect
@Component
public class LogAspect {
@Around("@annotation(com.example.demo.Loggable)")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
// 記錄日誌
Object result = joinPoint.proceed();
return result;
}
}
// 在方法上使用
@Service
public class DemoService {
@Loggable
public void doSomething() {
// ...
}
}
3. 如何集成Spring Security框架?
// 引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
// 配置安全策略
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("{noop}admin").roles("ADMIN");
}
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.and().httpBasic()
.and().csrf().disable();
}
}
// 在Controller中使用
@RestController
@RequestMapping("/admin")
public class AdminController {
@GetMapping("/welcome")
public String welcome() {
return "Welcome admin!";
}
}
三、Spring Boot常用註解
1. @SpringBootApplication
@SpringBootApplication是Spring Boot項目中最關鍵的註解,它相當於使用了@ComponentScan、@EnableAutoConfiguration和@SpringBootConfiguration三個註解。通常會在項目的主類中使用,如下所示:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2. @RestController
@RestController是Spring MVC中的註解,表示該類中的所有方法都會自動返回JSON格式的數據。通常會在Controller中使用,如下所示:
@RestController
@RequestMapping("/demo")
public class DemoController {
@GetMapping("/{id}")
public DemoData getDemoData(@PathVariable Long id) {
// ...
}
}
3. @GetMapping
@GetMapping是Spring MVC中的註解,表示該方法處理的是HTTP GET請求。通常會在Controller中使用,如下所示:
@GetMapping("/{id}")
public DemoData getDemoData(@PathVariable Long id) {
// ...
}
4. @PostMapping
@PostMapping是Spring MVC中的註解,表示該方法處理的是HTTP POST請求。通常會在Controller中使用,如下所示:
@PostMapping("/")
public void createDemoData(@RequestBody DemoData data) {
// ...
}
5. @Autowired
@Autowired是Spring框架中的註解,表示自動裝配Bean。通常會在Service或Controller中使用,如下所示:
@Service
public class DemoService {
@Autowired
private DemoRepository repository;
}
四、Spring Boot配置
1. 配置文件
Spring Boot支持多種類型的配置文件,包括.properties、.yml和.xml格式的文件。其中,.yml文件通常被認為是Spring Boot配置文件中最簡潔和方便的格式。以下是一個典型的應用程序配置:
# application.yml
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: 123456
2. 配置優先順序
Spring Boot根據以下順序讀取配置文件,並根據優先順序進行覆蓋:
- 命令行參數:使用”–property=value”格式的命令行參數覆蓋配置文件中的屬性。
- Java系統屬性:使用”-Dproperty=value”格式的Java系統屬性覆蓋配置文件中的屬性。
- 環境變數:使用”SPRING_APPLICATION_JSON”和”SPRING_CONFIG_NAME”環境變數設置屬性。
- JNDI屬性:使用JNDI屬性覆蓋配置文件中的屬性。
- 默認屬性:配置文件中指定的默認屬性。
3. 自定義屬性
Spring Boot支持在配置文件中自定義屬性,並在代碼中使用,以下是一個典型的配置:
# application.yml
my:
property: hello
在代碼中,使用@Value註解即可獲取該屬性的值:
@Service
public class DemoService {
@Value("${my.property}")
private String myProperty;
}
五、Spring Boot測試
1. 單元測試
Spring Boot使用JUnit和Spring Test框架來支持單元測試。以下是一個典型的測試類:
@SpringBootTest
public class DemoServiceTest {
@Autowired
private DemoService service;
@Test
public void testAdd() {
// ...
}
}
2. 集成測試
Spring Boot使用Spring Test框架來支持集成測試。以下是一個典型的測試類:
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class DemoControllerIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@LocalServerPort
private int port;
@Test
public void testGetDemoData() {
// ...
}
}
六、Spring Boot部署
1. WAR部署
Spring Boot可以打包成WAR文件,並部署到Jetty、Tomcat和WebLogic等Servlet容器中。以下是在Spring Boot項目中修改打包方式的方法:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.example.demo.Application</mainClass>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
2. Jar部署
Spring Boot可以打包成Jar文件,並使用命令行方式運行應用程序。以下是在Spring Boot項目中修改打包方式的方法:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.example.demo.Application</mainClass>
</configuration>
</plugin>
</plugins>
</build>
3. Docker部署
使用Docker可以讓Spring Boot應用程序變得可移植和可伸縮。以下是一個Dockerfile文件的示例:
FROM maven:3.6.3-jdk-11 AS build
WORKDIR /app
COPY pom.xml .
RUN mvn dependency:go-offline
COPY src/ /app/src/
RUN mvn package
FROM adoptopenjdk/openjdk11:jre-11.0.11_9-alpine
EXPOSE 8080
COPY --from=build /app/target/demo-0.0.1-SNAPSHOT.jar /app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
原創文章,作者:VIIZN,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/371567.html