SpringBoot的基本使用(一)

1.什么是SpringBoot

引入:

springBoot使用习惯优于配置的理念,然项目快速运行起来,使用Spring Boot很容易创建一个独立运行的(运行jar,内嵌Servlet容器)、准生产级别的基于Spring框架的项目,使用Spring Boot可以不用或者很少使用Spring 配置

Spring Boot核心功能

独立运行的Spring项目:Spring Boot可以以jar包的形式独立运行,运行一个Spring Boot项目只需通过java -jar xx.jar来运行

内嵌的Servlet容器:Spring Boot可选择内嵌Tomcat、Jetty,无需以war包形式部署项目

提供starter简化Maven的配置,如使用spring-boot-starter-web时,会自动加入tomcat,webMvc,jackson,hibernate-validate的jar

自动配置Spring:Spring Boot 会根据在类路径中的jar包,类为jar包里的类自动配置Bean

准生产级别的应用监控:Spring Boot提供了基于http,ssh,telnet对运行时的项目进行监控

无代码生产和xml配置(spring 4.x中通过条件注解实现)

2.Spring Boot项目的搭建

使用STS:new →spring-start-project-service URL 

使用IDea:file-new -project-Spring Initializr-https://start.spring.io/

新建的Spring Boot项目的pom.xml文件如下:


<?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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
 
	<groupId>com.pingan</groupId>
	<artifactId>anhui</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
 
	<name>anhui</name>
	<description>Demo project for Spring Boot</description>
	<!--spring boot 父工程 -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.3.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<!--spring boot 编码 -->
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>
 
	<dependencies>
	<!-- 	<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
	-->            
	<!--spring boot web依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	<!--spring boot 测试相关-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<!--spring boot maven插件 -->
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
 
 
</project>

从上面可以看出:Spring Boot的项目打包方式:jar,父工程:spring-boot-start-parent,依赖:spring-boot-starter-web,maven插件spring-boot-maven-plugin

spring Boot项目结构如下:

从上面可以看出:

入口类:AnhuiApplication为应用程序入口类,在com.pingan.anhui包下,其他项目必须在其子包内.

启动方式:运行AnhuiApplication的main方法,或者通过springboot的maven插件

全局配置文件:application.properties(或者application.yml)

 

3.Spring Boot的核心

基本配置:

入口类和@SpringBootApplication注解:

入口类中有个main方法,它是标准的Java应用入口方法,用于启动Spring Boot项目,@SpringBootApplication是Spring Boot的核心注解,它是一个组合注解:包括了@SpringBootConfiguration,@EnableAutoConfiguration,@ComponentScan注解,其中@SpringBootConfiguration就是@Configuration配置类注解,@EnableAutoConfiguration是根据类路径配置的jar包依赖开自动配置的注解。

如:添加spring-boot-starter-web时,会自动加入tomcat,SpringMVC的依赖,并且对Tomcat和Spring MVC进行自动配置,Spring Boot会自动扫描@SpringBootApplication 所在类的同级包及以下包 的Bean,建议其他所有包都在@SpringBootApplication 所在包的子包里。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
		@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

	@AliasFor(annotation = EnableAutoConfiguration.class, attribute = "exclude")
	Class<?>[] exclude() default {};

	@AliasFor(annotation = EnableAutoConfiguration.class, attribute = "excludeName")
	String[] excludeName() default {};

	@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
	String[] scanBasePackages() default {};

	@AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
	Class<?>[] scanBasePackageClasses() default {};

}

关闭自动配置:

@EnableAutoConfiguration是根据类路径配置的jar包依赖开自动配置的注解。如果我们想要关闭特定的自动配置,那么需要我们使用@SpringBootApplication注解的exclude参数 ,如:排除数据源的自动注入。

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

Spring Boot的全局配置文件

Spring Boot使用一个全局的配置文件application.properties或者application.yml,放置在src/main/resources/下或者类路径的config下,我们可以通过在全局配置文件中对一些默认配置的配置值进行修改

server.port=8088                 tomcat默认端口从8080修改8088
server.context-path=/hello       默认访问路径/改为/hello
server.servlet-path = *.html 配DispatcherServlet的规则为:*.html
logging.file=D:/log/haofang.log  日志输出位置
logging.level.org.springframework=debug 打印spring日志的级别
spring.profiles.active=dev      配置环境为dev
debug=true
server.session-timeout=60  session超时时间,默认30min

starter pom的使用

Spring Boot为我们提供了简化企业级开发的绝大多数常见的starter pom,只要使用了应用场景所需的相关starter pom,就可以消除相关技术的配置得到Spring Boot为我们自动配置好的Bean。

spring Boot官方提供了很多的starter pom

spring-boot-starterspringboot核心starter ,包括自动配置,日志,yaml配置文件的支持 
spring-boot-starter-actuator准生产特性,用来监控和管理应用
spring-boot-starter-remote-shell提供基于ssh协议的监控和管理
spring-boot-starter-amqp使用spring-rabbit支持AMQP
spring-boot-starter-aop使用AOP和AspectJ支持面向切面编程
spring-boot-starter-batch对springBatch支持
spring-boot-starter-cache对SpringCache抽象的支持
spring-boot-starter-cloud-connectors对云平台(Cloud Foundry ,Heroku)提供的服务简化的连接方式
spring-boot-starter-data-elasticsearch对spring-data-elasticsearch的支持
spring-boot-starter-data-gemfire对分布式存储GemFire的支持
spring-boot-starter-data-jpa对jpa的支持,包括spring-data-jap,spring-orm,Hibernate
spring-boot-starter-data-mongodb通过spring-data-mongodb对mongodb的支持
spring-boot-starter-data-rest通过spring-data-rest-webmvc对spring Data reposity暴露为REST形式的服务
spring-boot-starter-data-solr通过spring-data-solr对Apache Solr的支持
spring-boot-starter-data-freemaker对Freemaker的支持
spring-boot-starter-data-groovy-templates对Groovy模版引擎的支持
spring-boot-starter-hateoas通过spring-hateoas对基于HATEOAS的REST形式的网络服务的支持
spring-boot-starter-hornetq通过HornetQ对JMS的支持
spring-boot-starter-integration对系统集成框架spring-integration的支持
spring-boot-starter-jdbc对JDBC数据库的支持
spring-boot-starter-jersey对Jersey REST形式的网络服务的支持
spring-boot-starter-jta-atomikos通过Atomikos对分布式事物的支持
spring-boot-starter-jta-bitronix通过Bitronix对分布式事物的支持
spring-boot-starter-mail对spring mail的支持
spring-boot-starter-mobile对spring mobile的支持
spring-boot-starter-mustache对Mustache模版引擎的支持
spring-boot-starter-redis对键值对内存数据库Redis的支持,包含spring-redis
spring-boot-starter-security对spring-security的支持
spring-boot-starter-social-facebook通过spring-social-facebook 对facebook的支持
spring-boot-starter-social-twitter通过spring-social-twitter 对twitter的支持
spring-boot-starter-social-linkedin通过spring-social-linkedin 对linkedin的支持
spring-boot-starter-thymeleaf对Thymeleaf模版引擎的支持,包含于spring的整合配置
spring-boot-starter-velocity对velocity模版引擎的支持
spring-boot-starter-web对web项目开发的支持,包含tomcat和spring-webmvc
spring-boot-starter-Tomcatspringboot默认容器tomcat
spring-boot-starter-Jettyjetty容器
spring-boot-starter-undertowUndertow容器
spring-boot-starter-logging默认日志输出框架Logback
spring-boot-starter-log4j支持log4j
spring-boot-starter-websocketwebsocket的支持
spring-boot-starter-ws

spring webservice的支持

如何自定义以starter pom

 

使用xml配置

Spring Boot提倡零配置,即无xml配置,但是有些特殊要求我们必须使用xml配置,我们可以通过@ImportResouce来加载xml配置

@ImportResource(value = {"classpath:xxx-context.xml","classpath:yyy-context.xml"})

 

外部配置:

命令行参数配置:

Spring Boot基于jar包运行,打成jar包的程序可以直接通过下面命令运行:

java -jar xx.jar

java-jarxx.jar--server.port=8088 修改tomcat端口号

常规属性配置:

常规Spring环境下,注入properties文件的值,通过@PropertySource指明properties文件的位置,通过@Value注入值

在Spring Boot里,如果在application.properties定义属性,可以使用@Value注解注入即可。

springboot 1.5之前使用:
添加@ConfigurationProperties注解,配置其prefix和location属性,然后在spring boot启动类中用@EnableConfigurationProperties激活配置类


1.5版本后取消@ConfigurationProperties的location属性,使用:
@PropertySource(value = "classpath:a.properties")指定位置(如果是在application.properties文件则不需要指定),配合@ConfigurationProperties注解的prefix指定前缀,即可完成自动注入属性
@ConfigurationProperties注解的2种使用方式,也是2种配置bean的使用方式

1.直接配置 @Component使用
    @Component
    @ConfigurationProperties(prefix = "com.example.demo")
    public class People {

        private String name;

        private Integer age;

        private List<String> address;

        private Phone phone;
    }   

2.直接在配置类的@Bean上使用,效果是一样的
        @Bean
        @ConfigurationProperties(prefix = "com.example.demo")
        public People people() {

            return new People();
        }


当然可以通过注入Environment对象,通过environment的getProperty(key)来获取

注意:使用@configurationProperties注解时 idea弹出 Spring Boot Annotion processor not found in classpath,因为1.5版本后取消@ConfigurationProperties的location属性导致找不到文件
解决方案:pom.xml添加以下

<dependency>
   <groupId> org.springframework.boot </groupId>
   <artifactId> spring-boot-configuration-processor </artifactId>
   <optional> true </optional>
</dependency>

Profile的配置:

Profile是Spring支持不同环境应对不同配置,全局的Profile配置使用:

application-{profile}.properties文件(如application-dev.properties),然后在application.properties文件中添加属性:

spring.profiles.active = dev来指定活动的Profile

 

4.SpringBoot的运行原理


SpringBoot的运行原理

自定义starter pom

 

 

 

 

 

  • 12
    点赞
  • 63
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值