在本文中,我们将从多个方面介绍如何搭建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/n/333792.html
微信扫一扫
支付宝扫一扫