盤點Spring Boot Starter的主力,看看哪幾個是你沒用過的
- 2019 年 11 月 1 日
- 筆記
作者|SimpleWu
cnblogs.com/SimpleWu/p/9798146.html
Spring Boot 簡介
Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。通過這種方式,Boot致力於在蓬勃發展的快速應用開發領域(rapid application development)成為領導者。
Spring Boot讓我們的Spring應用變的更輕量化。比如:你可以僅僅依靠一個Java類來運行一個Spring引用。你也可以打包你的應用為jar並通過使用java -jar來運行你的Spring Web應用。
Spring Boot的主要優點:
- 為所有Spring開發者更快的入門
- 開箱即用,提供各種默認配置來簡化項目配置
- 內嵌式容器簡化Web項目
- 沒有冗餘代碼生成和XML配置的要求
在下面的代碼中只要有一定基礎會發現這寫代碼實例非常簡單對於開發者來說幾乎是「零配置」。
Spring Boot 運行
開發工具:jdk8,IDEA,STS,eclipse(需要安裝STS插件)這些都支持快速啟動SpringBoot工程。我這裡就不快速啟動了,使用maven工程。學習任何一項技術首先就要精通HelloWord,那我們來跑個初體驗。
首先只用maven我們創建的maven工程直接以jar包的形式創建就行了,首先我們來引入SpringBoot的依賴
首先我們需要依賴SpringBoot父工程,這是每個項目中必須要有的。
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.5.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties>
我們啟動WEB模塊當然必須要引入WEB模塊的依賴
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
我們需要編寫一個SpringBoot啟動類,SpringbootFirstExperienceApplication.java
@SpringBootApplication public class SpringbootFirstExperienceApplication { public static void main(String[] args) { SpringApplication.run(SpringbootFirstExperienceApplication.class, args); }
到了這裡我們直接把他當成SpringMVC來使用就行了,不過這裡默認是不支持JSP官方推薦使用模板引擎,後面會寫到整合JSP。這裡我就不寫Controller了。
@SpringBootApplication:之前用戶使用的是3個註解註解他們的main類。分別是@Configuration,@EnableAutoConfiguration,@ComponentScan。由於這些註解一般都是一起使用,spring boot提供了一個統一的註解@SpringBootApplication。
注意事項:我們使用這個註解在不指定掃描路徑的情況下,SpringBoot只能掃描到和 SpringbootFirstExperienceApplication 同包或子包的Bean;
Spring Boot 目錄結構
在 src/main/resources 中我們可以有幾個文件夾:
- templates:用來存儲模板引擎的,Thymeleaf,FreeMarker,Velocity等都是不錯的選擇。
- static:存儲一些靜態資源,css,js 等。
- public:在默認 Spring Boot 工程中是不生成這個文件夾的,但是在自動配置中我們可以有這個文件夾用來存放公共的資源。
- application.properties:這個文件名字是固定的,Spring Boot 啟動會默認加載這些配置在這裏面可以配置端口號,訪問路徑,數據庫連接信息等等。這個文件非常重要,當然官方中推出了一個 yml 格式這是非常強大的數據格式。
整合 JdbcTemplate
引入依賴:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--引入JDBC模塊--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--引入數據庫驅動--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
配置 application.properties,雖然說是「零配置」但是這些必要的肯定要指定,否則它怎麼知道連那個數據庫?
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Drive
使用方式:
@Service public class EmployeeService { @Autowired private JdbcTemplate jdbcTemplate; public boolean saveEmp(String name,String email,String gender){ String sql = "insert into tal_employee values(null,?,?,?)"; int result = jdbcTemplate.update(sql, name,email,gender); System.out.println("result : " + result); return result > 0 ? true:false; } }
@RestController public class EmployeeController { @Autowired private EmployeeService employeeService; @RequestMapping("/save") public String insert(String name,String email,String gender){ boolean result = employeeService.saveEmp(name, email, gender); if(result){ return "success"; } return "error"; } }
這裡我們直接返回一個文本格式。
@RestController
在上面的代碼中我們使用到這個註解修改我們的 Controller 類而是不使用 @Controller 這個註解,其實中包含了 @Controller,同時包含 @ResponseBody 既然修飾在類上面那麼就是表示這個類中所有的方法都是 @ResponseBody 所以在這裡我們返回字符串在前台我們會以文本格式展示,如果是對象那麼它會自動轉換成 JSON 格式返回。
整合 JPA
同樣的整合 JPA 我們只需要啟動我們 Spring Boot 已經集成好的模塊即可,添加依賴:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</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-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies>
啟動 JPA 組件後直接配置數據庫連接信息就可以使用 JPA 功能。
Application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver
實體類:Employee.java
@Table(name="tal_employee") @Entity public class Employee implements Serializable{ @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @Column(name="last_Name") private String lastName; private String email; private String gender; //get set 省略 }
EmployeeDao接口:
public interface EmployeeDao extends JpaRepository<Employee, Integer>{ }
EmployeeController.java:
@Controller public class EmployeeController { @Autowired private EmployeeDao employeeDao; @ResponseBody @RequestMapping("/emps") public List<Employee> getEmployees(){ List<Employee> employees = employeeDao.findAll(); System.out.println(employees); return employees; } }
整合 MyBatis
引入依賴:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--引入對JDBC的支持--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--引入對logging的支持--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </dependency> <!-- SpringBoot MyBatis啟動器 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies>
配置 application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver ##############datasource classpath 數據連接池地址############## #spring.datasource.type=com.alibaba.druid.pool.DruidDataSource mybatis.mapper-locations=classpath:com/simple/springboot/mybatis/dao/mapper/*.xml #entity.class 指定我們實體類所在包位置 mybatis.type-aliases-package=com.simple.springboot.mybatis.entity
當然這裡還有很多屬性如果想要使用可以參考官方文檔。到了這裡其他就不寫了,把他當作 SSM 使用就 OK。
注意事項:在我們的 Dao 層接口中一定要在類上加上註解 @Mapper 否則無法掃描到。
AOP 功能使用
在我們 Spring Boot 中使用 AOP 非常簡單。
@Aspect @Component public class SpringBootAspect { /** * 定義一個切入點 * @author:SimpleWu * @Date:2018年10月12日 */ @Pointcut(value="execution(* com.simple.springboot.util.*.*(..))") public void aop(){} /** * 定義一個前置通知 * @author:SimpleWu * @Date:2018年10月12日 */ @Before("aop()") public void aopBefore(){ System.out.println("前置通知 SpringBootAspect....aopBefore"); } /** * 定義一個後置通知 * @author:SimpleWu * @Date:2018年10月12日 */ @After("aop()") public void aopAfter(){ System.out.println("後置通知 SpringBootAspect....aopAfter"); } /** * 處理未處理的JAVA異常 * @author:SimpleWu * @Date:2018年10月12日 */ @AfterThrowing(pointcut="aop()",throwing="e") public void exception(Exception e){ System.out.println("異常通知 SpringBootAspect...exception .." + e); } /** * 環繞通知 * @author:SimpleWu * @throws Throwable * @Date:2018年10月12日 */ @Around("aop()") public void around(ProceedingJoinPoint invocation) throws Throwable{ System.out.println("SpringBootAspect..環繞通知 Before"); invocation.proceed(); System.out.println("SpringBootAspect..環繞通知 After"); } }
任務調度
Spring Boot 已經集成好一個調度功能。
@Component public class ScheduledTasks { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); /** * 任務調度,每隔5秒執行一次 * @author:SimpleWu * @Date:2018年10月12日 */ @Scheduled(fixedRate = 1000) public void reportCurrentTime() { System.out.println("現在時間:" + dateFormat.format(new Date())); } }
然後啟動的時候我們必須要在主函數類上加上註解:@EnableScheduling(翻譯過來就是開啟調度)
/** * SpringBoot使用任務調度 * @EnableScheduling標註程序開啟任務調度 * @author :SimpleWu * @Date:2018年10月12日 */ @SpringBootApplication @EnableScheduling public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }