spring boot是java开发平台上最流行的web框架。Scala是在JVM上运行的静态类型的函数编程语言。大数据处理Spark框架就是Scala语言开发的。
本例子将spring boot框架集成到scala项目中。利用Spring security模块提供的用户权限管理。制作一个简单的用户登录及权限管理。
使用到的技术 spring boot web service,swagger, h2 数据库,spring boot JPA,spring security
<?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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>scala-spring-boot</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<name>A Camel Scala Route</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<scala.version>2.11.7</scala.version>
</properties>
<dependencyManagement>
<dependencies>
</dependencies>
</dependencyManagement>
<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>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- scala -->
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala.version}</version>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-compiler</artifactId>
<version>${scala.version}</version>
</dependency>
<!-- Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
</dependencies>
<build>
<defaultGoal>install</defaultGoal>
<sourceDirectory>src/main/scala</sourceDirectory>
<testSourceDirectory>src/test/scala</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<id>compile-scala</id>
<phase>compile</phase>
<goals>
<goal>add-source</goal>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile-scala</id>
<phase>test-compile</phase>
<goals>
<goal>add-source</goal>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<configuration>
<recompileMode>incremental</recompileMode>
<scalaVersion>${scala.version}</scalaVersion>
<args>
<arg>-deprecation</arg>
</args>
<jvmArgs>
<jvmArg>-Xms64m</jvmArg>
<jvmArg>-Xmx1024m</jvmArg>
</jvmArgs>
</configuration>
</plugin>
</plugins>
</build>
</project>
@SpringBootApplication
class ApiApplication
object ApiApplication extends App {
SpringApplication.run(classOf[ApiApplication], args :_*)
}
@RestController和@RequestMapping用于在Spring中创建RESTful Web服务。Scala中Controller示例如下
@RestController
@RequestMapping(path = Array("/api"))
class UserController(@Autowired val userService: UserService, @Autowired val dataSource: DataSource) {
@GetMapping(path = Array("/users"))
def getAllUsers(): Iterable[Users] = {
userService.listUsers()
}
@GetMapping(path = Array("/users/{id}"))
def getUser(@PathVariable id: Long): Users = {
userService.getUser(id)
}
@PostMapping(path = Array("/users"))
def createUser(@RequestBody users: Users): ResponseEntity[Long] = {
val id = userService.createUser(users)
new ResponseEntity(id, new HttpHeaders, HttpStatus.CREATED)
}
}
@Service
class UserService(@Autowired private val userRepository: UserRepository) {
@PreAuthorize("hasRole(‘admin‘)")
def listUsers(): Iterable[Users] = {
userRepository.findAll
}
@PreAuthorize("hasRole(‘user‘)")
@PostAuthorize("returnObject.username==principal.username || hasRole(‘admin‘)")
def getUser(id: Long):Users = {
userRepository.findOne(id)
}
@PreAuthorize("hasRole(‘admin‘)")
def createUser(users: Users): Long = {
userRepository.save(users)
users.id
}
}
DROP IF EXISTS authorities;
CREATE TABLE authorities (id bigint auto_increment not null, username varchar_ignorecase(50) not null, authority varchar_ignorecase(50) not null, constraint fk_authorities_users foreign key(username) references users(username));
INSERT INTO users (id, username, password,enabled) VALUES (1, ‘root‘, ‘root‘, true), (2, ‘user‘, ‘user‘, true);
INSERT INTO authorities (id, username, authority) VALUES (1, ‘root‘, ‘ROLE_user‘), (2, ‘root‘, ‘ROLE_admin‘), (3, ‘user‘, ‘ROLE_user‘);
@Repository
trait UserRepository extends CrudRepository[Users, Long] {
def findUserByUsername(username: String): Users
}
注意 这里id的类型必须是java.lang.Long 不能是scala原生Long。原因是CrudRepository 的ID 类型必须是继承Serializable
@Entity
class Users extends Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@BeanProperty
var id: Long = _
@BeanProperty
@Column(name = "username")
var username: String = _
@BeanProperty
@Column(name = "password")
var password: String = _
@BeanProperty
@Column(name = "enabled")
var enabled: Boolean = _
}
spring.h2.console.enabled=true是允许通过控制台访问H2数据库
spring.datasource.url=jdbc:h2:~/test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=sa
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
# h2
spring.h2.console.enabled=true
@Configuration
@EnableSwagger2
class SwaggerConfig {
@Bean
def api(): Docket = {
new Docket(DocumentationType.SWAGGER_2).select.apis(RequestHandlerSelectors.any).paths(PathSelectors.any).build
}
}
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
class WebSecurityConfig(@Autowired val dataSource: DataSource) extends WebSecurityConfigurerAdapter {
override def configure(http: HttpSecurity) = {
http.authorizeRequests.antMatchers("/console", "/console/**", "/console/", "/swagger-ui.html", "/**/*.css", "/**/*.js", "/**/*.png", "/configuration/**", "/swagger-resources", "/v2/**").permitAll
http.authorizeRequests.anyRequest.authenticated
http.csrf.disable
http.headers.frameOptions.disable
http.httpBasic
}
@Bean override def userDetailsService: UserDetailsService = {
val manager = new JdbcDaoImpl
manager.setDataSource(dataSource)
manager
}
}
-示例代码
@Test
def testPostCreateUser() = {
val headers = new HttpHeaders
headers.add("Authorization", "Basic " + new String(Base64.encodeBase64(("root" + ":" + "root").getBytes)))
headers.setContentType(MediaType.APPLICATION_JSON)
headers.setAccept(util.Arrays.asList(MediaType.APPLICATION_JSON))
val user = new Users
user.setId(101L)
user.setUsername("Test")
user.setPassword("Test")
user.setEnabled(true)
val entity = new HttpEntity(user, headers)
val result = template.postForObject("/api/users", entity, classOf[String])
println(result)
}
原文:https://www.cnblogs.com/carl-coding/p/9367589.html