摘要:版本和編碼方式依賴管理這樣比如使用的時候就不需要指定版本號使用自己的項目這時候?qū)⒁蕾嚬芾淼膯栴}放到中。
1 Pom文件
1.1 spring-boot-starter-parent
表示當(dāng)前pom文件從spring-boot-starter-parent繼承下來,在spring-boot-starter-parent中提供了很多默認(rèn)配置,可以簡化我們的開發(fā)。
org.springframework.boot spring-boot-starter-parent 2.1.4.RELEASE
Java版本和編碼方式
UTF-8 1.8 @ ${java.version} UTF-8 ${java.version}
依賴管理spring-boot-dependencies
5.15.9 2.7.7 1.9.73 2.6.4 ...
這樣比如使用starter-web的時候就不需要指定版本號
org.springframework.boot spring-boot-starter-web 2.1.4.RELEASE
使用自己的parent項目
這時候?qū)⒁蕾嚬芾淼膯栴}放到dependencyManagement中。
官網(wǎng)說明文檔見:13.2.2 Using Spring Boot without the Parent POM
org.springframework.boot spring-boot-dependencies 2.1.4.RELEASE pom import
1.2 打包管理
使用mvn package打包的plugin。
org.springframework.boot spring-boot-maven-plugin
1.3 Starters
官網(wǎng)見:13.5 Starters
Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop shop for all the Spring and related technologies that you need without having to hunt through sample code and copy-paste loads of dependency descriptors. For example, if you want to get started using Spring and JPA for database access, include the spring-boot-starter-data-jpa dependency in your project.
官方starter命名
spring-boot-starter-*
自定義starter命名
thirdpartyproject-spring-boot-starter
spring-boot-web-starter
查看其diagram,可以排除某個依賴
org.springframework.boot spring-boot-starter-tomcat
2 XXXApplication
2.1 @SpringBootApplication
官網(wǎng)見:18. Using the @SpringBootApplication Annotation
等同于@EnableAutoConfiguration,@ComponentScan和@Configuration
2.2 SpringApplication.run
官網(wǎng)見:23. SpringApplication
3 配置文件
3.1 初步感受
server.port=9090
3.2 yml文件
application.yml
3.3 給屬性注入值
實體類Person和IDCard
public class Person {
private String name; private int age; private Date birthday; private String[] hobbies; private IDCard idCard; ...
}
public class IDCard {
private int id; private String number;
}
yml注入寫法
person:
name: Jack age: 17 birthday: 1997/06/01 hobbies: [code,sing,share] idCard: id: 1 number: 111
Person類增加注解
@Component
@ConfigurationProperties(prefix="person")
測試
@Autowired
private Person person;
如果Person類上報錯,在Pom文件中加入如下依賴
org.springframework.boot spring-boot-configuration-processor
4 處理動靜態(tài)資源
4.1 動態(tài)資源
官網(wǎng)見:90.2 Reload Templates without Restarting the Container
templates
resources目錄下有一個templates文件夾,可以將動態(tài)資源放到其中
引入thymeleaf
org.springframework.boot spring-boot-starter-thymeleaf
templates下新建test.html文件
controller中return test
@Controller
@RequestMapping("/gupao")
public class GupaoController {
@RequestMapping("/hello") public String hello(Model model){ String str="hello spring boot"; //想要動態(tài)的顯示在網(wǎng)頁當(dāng)中 model.addAttribute("str",str); //接下來的頁面是能夠動態(tài)顯示傳過來的數(shù)據(jù) return "test"; }
}
4.2 靜態(tài)資源
static文件夾
在resources目錄下有一個static文件夾,可以將靜態(tài)資源放到其中,瀏覽器可以直接訪問。
靜態(tài)資源其他存放文件夾
"classpath:/META-INF/resources/"
"classpath:/resources/"
"classpath:/static/"
"classpath:/public/"
WebMvcAutoConfiguration源碼分析
WebMvcAutoConfiguration--->WebMvcAutoConfigurationAdapter.addResourceHandlers(xxx)--->
this.resourceProperties.getStaticLocations()
return this.staticLocations;
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" };
自定義靜態(tài)資源文件夾
觀察
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {
配置application.properties
spring.resources.static-locations=classpath:/gupao/
5 整合MyBatis
5.1 需求
通過Spring Boot Web項目api接口的方式,整合MyBatis實現(xiàn)crud的操作。
5.2 創(chuàng)建Spring Boot Web項目
重溫一下web項目創(chuàng)建的過程。
5.3 引入項目中需要的starter依賴
5.4 創(chuàng)建數(shù)據(jù)庫表
db_gupao_springboot--->t_user
5.5 創(chuàng)建domain/User對象
public class User {
private int id; private String username; private String password; private String number; ...
}
5.6 開發(fā)dao層
@Repository
@Mapper
public interface UserMapper {
User find(String username); Listlist(); int insert(User user); int delete(int id); int update(User user);
}
5.7 開發(fā)service層
@Service
public class UserService {
@Autowired public UserMapper userMapper; public User findByUsername(String username){ return userMapper.find(username); } public ListlistUser(){ return userMapper.list(); } public int insertUser(User user){ return userMapper.insert(user); } public int updateUser(User user){ return userMapper.update(user); } public int delete(int id){ return userMapper.delete(id); }
}
5.8 開發(fā)controller層
@RestController
@RequestMapping(value="/user",method = {RequestMethod.GET,RequestMethod.POST})
public class UserController {
@Autowired private UserService userService; @RequestMapping("/listone") @ResponseBody public User listOne(String username){ return userService.findByUsername(username); } @RequestMapping("/listall") @ResponseBody public ListlistAll(){ return userService.listUser(); } @RequestMapping(value="/add",method= RequestMethod.POST) @ResponseBody public String add(User user){ int result=userService.insertUser(user); if(result>=1) { return "添加成功"; }else{ return "添加失敗"; } } @RequestMapping(value="/update",method= RequestMethod.POST) @ResponseBody public String update(User user){ int result=userService.updateUser(user); if(result>=1) { return "修改成功"; }else{ return "修改失敗"; } } @RequestMapping(value="/delete",method= RequestMethod.GET) @ResponseBody public String delete(int id){ int result=userService.delete(id); if(result>=1) { return "刪除成功"; }else{ return "刪除失敗"; } }
}
5.9 resources目錄下創(chuàng)建mapper文件夾---UserMapper.xml
"-//mybatis.org//DTD com.example.Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
INSERT INTO t_user ( id,username,password,number ) VALUES ( #{id}, #{username, jdbcType=VARCHAR}, #{password, jdbcType=VARCHAR}, #{number} )
delete from t_user where id=#{id}
update t_user set user.username=#{username},user.password=#{password},user.number=#{number} where user.id=#{id}
5.10 application.properties文件配置
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/boot?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Drivermybatis托管mapper文件
mybatis:
mapper-locations: classpath:mapper/*.xml
5.11 啟動項目測試
查詢
http://localhost:8888/user/listone?username=Jack
全部查詢
http://localhost:8888/user/listall
增加
http://localhost:8888/user/add?id=3&username=AAA&password=111111&number=300
更新
http://localhost:8888/user/update?id=3&username=BBB
刪除
http://localhost:8888/user/delete?id=3
6 項目打包
jar包
mvn -Dmaven.test.skip -U clean install
java -jar xxx.jar
war包
7 Spring Boot in less than 10 minutes
https://www.youtube.com/watch...
BUILD ANYTHING WITH SPRING BOOT
Spring Boot is the starting point for building all Spring-based applications. Spring Boot is designed to get you up and running as quickly as possible, with minimal upfront configuration of Spring.
Get started in seconds using Spring Initializr
Build anything: REST API, WebSocket, web, streaming, tasks, and more
Simplified security
Rich support for SQL and NoSQL
Embedded runtime support: Tomcat, Jetty, and Undertow
Developer productivity tools such as LiveReload and Auto Restart
Curated dependencies that just work
Production-ready features such as tracing, metrics, and health status
Works in your favorite IDE: Spring Tool Suite, IntelliJ IDEA, and NetBeans
7.1 IDEA創(chuàng)建工程
group:com.example
artifact:bootiful
dependencies:Reactive Web,Reactive MongoDB,Lombok,Actuator,Security
7.2 DATA DRIVE
Spring Data integrates seamlessly with SQL and NoSQL persistence stores. Spring Data supports reactive data access,too!
@Component
class DataWriter implements ApplicationRunner {
private final CustomerRepository customerRepository; DataWriter(CustomerRepository customerRepository) { this.customerRepository = customerRepository; } @Override public void run(ApplicationArguments args) throws Exception { Flux.just("Jack", "Rechal", "Richard", "Jobs") .flatMap(name -> customerRepository.save(new Customer(null, name))) .subscribe(System.out::println); }
}
interface CustomerRepository extends ReactiveMongoRepository
}
@Document
@NoArgsConstructor
@Data
class Customer {
private String id,name; public Customer(String id, String name) { this.id = id; this.name = name; }
}
7.3 REST
On the web,nobody knows you"re a reactive microservice.
@SpringBootApplication
public class BootifulApplication {
@Bean RouterFunctionroutes(CustomerRepository cr){ return RouterFunctions.route(GET("/customers"),serverRequest -> ok().body(cr.findAll(),Customer.class)); } public static void main(String[] args) { SpringApplication.run(BootifulApplication.class, args); }
}
7.4 OBSERVABILITY
How"s your app"s health?Who better to articulate that then the application itself?
Spring Boot featurese strong opinions,loosely held.
It"s easy to change any of them with properties or pluggable implementations
management.endpoint.health.show-details=always
management.endpoints.web.exposure.exclude=*
@Bean
HealthIndicator healthIndicator(){
return () -> Health.status("I <3 Production").build();
}
訪問:curl http://localhost:8080/actuator/health | jq
7.5 SECURITY
Effortlessly plugin authentication and authorization in a traditional or reactive application with Spring Security
@Bean
MapReactiveUserDetailsService users(){
return new MapReactiveUserDetailsService(User.withDefaultPasswordEncoder().username("user").password("pw").roles("USER").build());
}
訪問:curl -vu user:pw http://localhost:8080/customers | jq
7.6 TO PRODUCTION
Let"s provision a MongoDB instance,configure our application"s route and MongoDB binding,and then push our application to production with Cloud Foundry.
命令切換到bootiful根目錄下
cf services
定位到my-mongodb文件夾
復(fù)制對應(yīng)文件,修改和觀察
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/77866.html
摘要:采用一套固化的認(rèn)知來建立生產(chǎn)環(huán)境準(zhǔn)備的應(yīng)用。我們采用一套關(guān)于固化平臺和第三包依賴庫的認(rèn)知,以至于你可以通過最小的煩惱來啟動。大多數(shù)的應(yīng)用程序只需要非常少的配置。 1 Spring Boot官網(wǎng)[2.1.5 CURRENT GA] 1.1 Pivotal Wiki Pivotal Software, Inc. is a software and services company base...
摘要:注解分析注解定義注解,用于為代碼提供元數(shù)據(jù)。我們可以將元注解看成一種特殊的修飾符,用來解釋說明注解,它是注解的元數(shù)據(jù)。被修改的注解,結(jié)合可以指定該注解存在的聲明周期。新增的可重復(fù)注解。 Spring Boot 注解分析 1 注解1.1 定義Annotation(注解),用于為Java代碼提供元數(shù)據(jù)。簡單理解注解可以看做是一個個標(biāo)簽,用來標(biāo)記代碼。是一種應(yīng)用于類、方法、參數(shù)、變量、構(gòu)造器...
摘要:認(rèn)證鑒權(quán)與權(quán)限控制在微服務(wù)架構(gòu)中的設(shè)計與實現(xiàn)一引言本文系認(rèn)證鑒權(quán)與權(quán)限控制在微服務(wù)架構(gòu)中的設(shè)計與實現(xiàn)系列的第一篇,本系列預(yù)計四篇文章講解微服務(wù)下的認(rèn)證鑒權(quán)與權(quán)限控制的實現(xiàn)。 java 開源項目收集 平時收藏的 java 項目和工具 某小公司RESTful、共用接口、前后端分離、接口約定的實踐 隨著互聯(lián)網(wǎng)高速發(fā)展,公司對項目開發(fā)周期不斷縮短,我們面對各種需求,使用原有對接方式,各端已經(jīng)很...
摘要:殺只雞而已,你拿牛刀來做甚釋義小團隊小項目選擇簡單的配置管理方式就好了,要什么配置中心,純屬沒事找事。,我就啰嗦到這里吧,下面正式介紹作為配置中心是怎么使用的。 前言 在看正文之前,我想請你回顧一下自己待過的公司都是怎么管理配置的,我想應(yīng)該會有以下幾種方式: 1、硬編碼沒有什么配置不配置的,直接寫在代碼里面,比如使用常量類優(yōu)勢:對開發(fā)友好,開發(fā)清楚地知道代碼需要用到什么配置劣勢:涉及秘...
摘要:它使用約定大于配置的理念讓你的項目快速運行起來。如何使用構(gòu)建工程第一步,當(dāng)然是安裝傻瓜式教程,請自行百度。包名,填完和后自動生成,默認(rèn)即可。確認(rèn)無誤,點完成創(chuàng)建即可。 微信公眾號:一個優(yōu)秀的廢人如有問題或建議,請后臺留言,我會盡力解決你的問題。 前言 新年立了個 flag,好好運營這個公眾號。具體來說,就是每周要寫兩篇文章在這個號發(fā)表。剛立的 flag 可不能這么快打臉。下面送上本周第...
閱讀 3933·2021-09-22 10:02
閱讀 3365·2019-08-30 15:52
閱讀 3060·2019-08-30 12:51
閱讀 753·2019-08-30 11:08
閱讀 2064·2019-08-29 15:18
閱讀 3105·2019-08-29 12:13
閱讀 3591·2019-08-29 11:29
閱讀 1872·2019-08-29 11:13