在本文中,我們將從多個方面介紹如何搭建SpringBoot應用程序。在開始之前,我們需要確保已經安裝了Java和Maven。本文中使用的是SpringBoot 2.5.2和Java 8。
一、創建SpringBoot項目
第一步是創建一個新的SpringBoot項目。在此之前,請確保您在計算機上安裝了Maven。
打開命令行窗口,進入您要創建項目的目錄。鍵入以下命令:
mvn archetype:generate -DgroupId=com.example -DartifactId=demo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
這會創建一個新的Maven項目,並且項目結構應該是類似於以下內容:
demo
|-- pom.xml
`-- src
|-- main
| |-- java
| | `-- com
| | `-- example
| | `-- App.java
| `-- resources
| `-- application.properties
`-- test
|-- java
| `-- com
| `-- example
| `-- AppTest.java
`-- resources
`-- test.properties
現在,在您的項目目錄中,創建一個新的maven module。可以通過右鍵點擊項目,選擇「New -> Module」來完成。在「New Module」窗口中,選擇「Spring Initializr」選項,然後點擊「Next」。
在「New Spring Initializr Project」窗口中,填寫相關信息,然後點擊「Next」:
- Group: com.example
- Artifact: demo
- Description: Spring Boot Demo
- Package: com.example.demo
- Packaging: Jar
- Java: 8
- Spring Boot: 2.5.2
點擊「Next」之後,您可以添加一些起始依賴項。在本文檔中,我們將使用默認設置。點擊「Finish」以完成創建過程。
二、創建RESTful API
RESTful API是用於處理HTTP請求的一種Web服務。在Spring Boot中,我們可以使用Spring MVC模塊來創建RESTful API。讓我們來創建一個簡單的舉例RESTful API。
首先,我們需要添加所需的Maven依賴項。在您的項目的pom.xml文件中,添加以下依賴項:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
這個依賴包含了Spring MVC和Tomcat。接下來,創建一個控制器類來處理HTTP請求,例如:
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, world!";
}
}
在這個類中,我們使用Spring的@RestController註解來表示這是一個控制器類,並且使用@GetMapping註解來指定對應的HTTP請求路徑。
現在,啟動應用程序,使用Web瀏覽器或curl命令測試API。用Web瀏覽器打開http://localhost:8080/hello。如果一切正常,您應該會看到一個網頁,顯示「Hello, world!」字樣。
三、添加數據庫連接和JPA支持
Now,我們來看一下如何添加數據庫連接和JPA支持。在本例中,我們選擇MySQL數據庫。
首先,添加MySQL連接驅動程序和Spring Data JPA庫到pom.xml:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
接下來,配置數據庫連接,打開application.properties文件,加上mysql相關的配置信息:
spring.datasource.url=jdbc:mysql://localhost:3306/demo spring.datasource.username=root spring.datasource.password= spring.jpa.hibernate.ddl-auto=create spring.jpa.database=mysql spring.jpa.show-sql=true
在這個例子中,我們假設MySQL數據庫是運行在默認端口3306,並且使用了一個名為「demo」的數據庫。請根據您自己的設置進行適當的修改。
下一步,創建實體類和相應的存儲庫。在本例中,我們使用JPA自動生成ID的默認行為:
package com.example.demo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
接下來,創建一個Repository類,用於操作Person實體類的信息:
package com.example.demo;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PersonRepository extends JpaRepository<Person, Long> {}
最後,為Person實體類創建一個RESTful API。這個API允許我們使用HTTP請求來添加和查詢Person實體。
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
@RestController
@RequestMapping("/person")
public class PersonController {
@Autowired
private PersonRepository personRepository;
@GetMapping("/{id}")
public Optional<Person> getPerson(@PathVariable Long id) {
return personRepository.findById(id);
}
@PostMapping
public Person addPerson(@RequestBody Person person) {
return personRepository.save(person);
}
}
在這裡,我們使用了Spring的自動依賴注入來注入PersonRepository bean,並且通過使用@PostMapping和@GetMapping註解來指定對應的HTTP請求路徑。
現在,啟動應用程序,並測試這個API。您可以使用curl命令來測試POST方法:
curl -d '{"name":"Jack"}' -H "Content-Type: application/json" -X POST http://localhost:8080/person
檢索Person實體:
curl http://localhost:8080/person/1
如果一切正常,您應該會看到JSON格式的Person實體信息。
四、添加安全支持
最後,讓我們看一下如何添加安全支持。在本例中,我們選擇使用Spring Security框架。
首先,我們需要添加Spring Security依賴項以及必要的存儲庫和服務。修改pom.xml文件,添加以下依賴項:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-data</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
接下來,創建一個SecurityConfig類,用於定義安全規則。在本例中,我們定義了一個「admin」用戶和一個「user」用戶,每個用戶都有不同的角色,並且只有具有相應角色的用戶才可以訪問相應的API。
package com.example.demo;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("{noop}password").roles("ADMIN")
.and()
.withUser("user").password("{noop}password").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/hello").permitAll()
.antMatchers(HttpMethod.POST, "/person").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
在這裡,我們定義了兩個用戶「admin」和「user」。每個用戶都有一個密碼,並且具有不同的角色。使用withUser定義用戶,並將它們添加到inMemoryAuthentication中。這裡需要使用{noop}前綴將密碼指定為明文。
然後,我們使用@EnableGlobalMethodSecurity(prePostEnabled = true)註解來啟用Spring Security的方法級別的訪問控制,並使用@PreAuthorize("hasRole('ADMIN')")註解來定義訪問規則。
最後,我們在configure(HttpSecurity http)方法中定義了Spring Security的HTTP請求處理規則。我們限定了只有具有ROLE_ADMIN角色的用戶才可以訪問POST /person API,並使用HTTP Basic身份驗證機制來保護其他API。
現在,啟動應用程序,並使用curl命令來測試API:
使用admin賬戶更新Person實體:
curl -d '{"name":"John"}' -H "Content-Type: application/json" -u admin:password -X POST http://localhost:8080/person
使用user賬戶檢索Person實體:
curl -u user:password http://localhost:8080/person/1
如果一切正常,您應該會看到JSON格式的Person實體信息。
原創文章,作者:MYBKR,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/333792.html
微信掃一掃
支付寶掃一掃