🔍
📢

 

Spring Boot & Spring Security 最佳实践

 

vim Hi.java

package com.example;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication public class Hi { public static void main(String[] args) { SpringApplication.run(Main.class, args); } }
@RestController class HelloWorld { @RequestMapping("/") public String helloworld() { return "Hello, World!"; } }

// [可选 - 仅用于Spring Security] @EnableWebSecurity class WSCA extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // http 404 example - http://localhost:8080/new/404 http.authorizeRequests().antMatchers("/new/**").permitAll();

super.configure(http); } }




build.gradle

 apply plugin: 'java'
...
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web:2.3.0.RELEASE'

// [可选] 启用Form Login表单登录页
// 表单登录默认用户名是user 密码则会输出在控制台 - Using generated security password: 随机生成
implementation 'org.springframework.boot:spring-boot-starter-security:2.3.0.RELEASE'
}




[可选] Spring Security配置文件:
src/main/resources/application.yml

#   更改内置错误页路径 /error 至 /new/error
server:
  error:
    path: /new/error
#   设定默认用户名和密码
spring:
  security:
    user:
      name: user
      password: user



Run
gradle -PrunClassName=com.example.Hi runSingle

访问网址和默认端口 - http://localhost:8080/