初学spring boot,遇到的第一个坎就是好多注解都不知道作用,即使照猫画虎把代码敲出来运行成功,也没有些许成就感。原因其实很简单,我觉得自己还没真的学会。接下来就是找资料,理解原理与过程,不求理解的深度,起码也得把自己说服了。本文档是从英语文档翻译过来,外加了一些自己的理解,其中表述错误的地方还望留言指正。
源文档链接:http://zetcode.com/springboot/repository/
@Repository
注解修饰哪个类,则表明这个类具有对对象进行CRUD(增删改查)的功能,而且@Repository
是@Component
注解的一个派生品,所以被@Repository
注解的类可以自动的被@ComponentScan
通过路径扫描给找到。(这也在一定程度上解释了,为什么被@Repository
注解的类也能@Autowired
)
下面这个例子将会讲述@Repository
的用法,这个例子展示的是HTML表中的国家/地区列表。该程序使用的Spring boot 2.1.0版本。
pom.xml
src
├───main
│ ├───java
│ │ └───com
│ │ └───zetcode
│ │ │ Application.java
│ │ ├───controller
│ │ │ MyController.java
│ │ ├───model
│ │ │ Country.java
│ │ ├───repository
│ │ │ CountryRepository.java
│ │ └───service
│ │ CountryService.java
│ │ ICountryService.java
│ └───resources
│ │ application.yml
│ │ import.sql
│ ├───static
│ │ index.html
│ └───templates
│ showCountries.ftl
└───test
└───java
这是工程架构。
pom.xml
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.zetcodegroupId>
<artifactId>repositoryexartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>jarpackaging>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>11maven.compiler.source>
<maven.compiler.target>11maven.compiler.target>
properties>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.1.0.RELEASEversion>
parent>
<dependencies>
<dependency>
<groupId>com.h2databasegroupId>
<artifactId>h2artifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-freemarkerartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-jpaartifactId>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
这是Maven build文件,h2依赖包括H2数据库驱动。
Spring boot starters是一系列非常方便的依赖描述符,它大大简化了maven的配置。spring-boot-start-parent
包含spring boot application的常用配置;spring-boot-devtools
包含spring boot的开发工具;spring-boot-starter-web
支持classic和RESTFul的web应用程序启动;spring-boot-starter-web-freemarker
是构建基于Freemarker模板引擎的web应用程序的启动器,它采用Tomcat作为默认的嵌入式容器。spring-boot-starter-data-jpa
是基于Hibernate的Spring Data JPA的启动器。
resources/application.yml
server:
port: 8086
servlet:
context-path: /SpringBootRepository
spring:
main:
banner-mode: "off"
jpa:
database: h2
hibernate:
dialect: org.hibernate.dialect.H2Dialect
ddl-auto: create-drop
logging:
level:
org:
springframework: ERROR
在application.yml
文件中,我们编写了spring boot应用程序的各种配置,服务器的端口和上下文的路径。完成这些设置后,我们通过localhost:8086/SpringBootRepository/
访问应用程序。在该文件配置中关闭了banner-mode
。
resources/import.sql
INSERT INTO countries(name, population) VALUES('China', 1382050000);
INSERT INTO countries(name, population) VALUES('India', 1313210000);
INSERT INTO countries(name, population) VALUES('USA', 324666000);
INSERT INTO countries(name, population) VALUES('Indonesia', 260581000);
INSERT INTO countries(name, population) VALUES('Brazil', 207221000);
INSERT INTO countries(name, population) VALUES('Pakistan', 196626000);
INSERT INTO countries(name, population) VALUES('Nigeria', 186988000);
INSERT INTO countries(name, population) VALUES('Bangladesh', 162099000);
INSERT INTO countries(name, population) VALUES('Nigeria', 186988000);
INSERT INTO countries(name, population) VALUES('Russia', 146838000);
INSERT INTO countries(name, population) VALUES('Japan', 126830000);
INSERT INTO countries(name, population) VALUES('Mexico', 122273000);
INSERT INTO countries(name, population) VALUES('Philippines', 103738000);
INSERT INTO countries(name, population) VALUES('Ethiopia', 101853000);
INSERT INTO countries(name, population) VALUES('Vietnam', 92700000);
INSERT INTO countries(name, population) VALUES('Egypt', 92641000);
INSERT INTO countries(name, population) VALUES('Germany', 82800000);
INSERT INTO countries(name, population) VALUES('the Congo', 82243000);
INSERT INTO countries(name, population) VALUES('Iran', 82800000);
INSERT INTO countries(name, population) VALUES('Turkey', 79814000);
INSERT INTO countries(name, population) VALUES('Thailand', 68147000);
INSERT INTO countries(name, population) VALUES('France', 66984000);
INSERT INTO countries(name, population) VALUES('United Kingdom', 60589000);
INSERT INTO countries(name, population) VALUES('South Africa', 55908000);
INSERT INTO countries(name, population) VALUES('Myanmar', 51446000);
INSERT INTO countries(name, population) VALUES('South Korea', 68147000);
INSERT INTO countries(name, population) VALUES('Colombia', 49129000);
INSERT INTO countries(name, population) VALUES('Kenya', 47251000);
INSERT INTO countries(name, population) VALUES('Spain', 46812000);
INSERT INTO countries(name, population) VALUES('Argentina', 43850000);
INSERT INTO countries(name, population) VALUES('Ukraine', 42603000);
INSERT INTO countries(name, population) VALUES('Sudan', 41176000);
INSERT INTO countries(name, population) VALUES('Algeria', 40400000);
INSERT INTO countries(name, population) VALUES('Poland', 38439000);
创建完数据库和表后,执行上这个sql脚本用其中的数据填充表。
com/zetcode/model/Country.java
package com.zetcode.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Objects;
@Entity
@Table(name = "countries")
public class Country {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int population;
public Country() {
}
public Country(Long id, String name, int population) {
this.id = id;
this.name = name;
this.population = population;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Country country = (Country) o;
return population == country.population &&
Objects.equals(id, country.id) &&
Objects.equals(name, country.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name, population);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Country{");
sb.append("id=").append(id);
sb.append(", name='").append(name).append('\'');
sb.append(", population=").append(population);
sb.append('}');
return sb.toString();
}
}
Country
是一个实例,每一个实力必须包含这两个注解@Entity
和@Id
。以前,我们必须将ddl-auto
选项设置成create-drop
表明Hibernate将从这个实例中构建表。
@Entity
@Table(name = "countries")
public class Country {
@Entity
注解指明该类是一个实例并且将会映射成一个数据库表。@Table
注解指定了这个数据库表的名字。
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Id指定了这个实例的主键,@GeneratedValue
规定了这个主键的值得生成策略。
com/zetcode/repository/CountryRepository.java
package com.zetcode.repository;
import com.zetcode.bean.Country;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CountryRepository extends CrudRepository<Country, Long> {
}
CountryRepository
被@Repository
注解,通过继承springCrudRepository
,CountryRepository拥有了对数据进行CRUD的方法,包括findAll()
。
com/zetcode/service/ICountryService.java
package com.zetcode.service;
import com.zetcode.bean.Country;
import java.util.List;
public interface ICountryService {
public List<Country> findAll();
}
ICountryService
接口中定义了一个findall()
方法。
com/zetcode/service/CountryService.java
package com.zetcode.service;
import com.zetcode.model.Country;
import com.zetcode.repository.CountryRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CountryService implements ICountryService {
@Autowired
private CountryRepository repository;
@Override
public List<Country> findAll() {
var countries = (List<Country>) repository.findAll();
return countries;
}
}
CountryService
继承ICountryService
并实现findAll()
方法。
@Autowired
private CountryRepository repository;
用@Autowired
注解CountryRepository
。
@Override
public List findAll() {
var countries = (List) repository.findAll();
return countries;
}
findAll()
方法的返回值是数据库表中所有国家的列表。
com/zetcode/controller/MyController.java
package com.zetcode.controller;
import com.zetcode.model.Country;
import com.zetcode.service.ICountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.List;
@Controller
public class MyController {
@Autowired
ICountryService countryService;
@RequestMapping("/showCountries")
public ModelAndView findCities() {
var countries = (List<Country>) countryService.findAll();
var params = new HashMap<String, Object>();
params.put("countries", countries);
return new ModelAndView("showCountries", params);
}
}
MyController
接收一个来自客户端的请求。
@Controller
public class MyController {
MyController
这个controller被@controller
注解。
@Autowired
ICountryService countryService;
ICountryService
被注入成员变量countryService
中。
var countries = (List<Country>) countryService.findAll();
我们用findAll()
方法取回了所有的国家。
Application.java
package com.zetcode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Application
是启动Spring boot应用程序的入口。@SpringBootApplication
注解支持自动配置和组件扫描。它可以代替@Configuration
,@ EnableAutoConfiguration
和@ComponentScan
三个注解的功能。