SpringBoot框架

SpringBoot框架,第1张

SpringBoot框架 SpringBoot-第一天 1.学习目标

1.Spring框架发展史

2.Spring5.x应用零配置开发

3.SpringMVC应用零配置开发与部署

4.SpringBoot框架概念,优势与快速入门

5.SpringBoot核心配置

6.Freemarker & Thymeleaf模板集成

7.SpringBoot静态资源文件添加与访问

8.SpringBoot应用打包与部署

2.Spring框架的发展史 2.1. Spring1.x 时代

在 Spring1.x 时代,都是通过 xml ⽂件配置 bean,随着项⽬的不断扩⼤,需要将 xml 配置分放到不同 的配置⽂件中,需要频繁的在 java 类和 xml 配置⽂件中切换。

2.2. Spring2.x 时代

随着 JDK 1.5 带来的注解⽀持,Spring2.x 可以使⽤注解对Bean进⾏声明和注⼊,⼤⼤的减少了 xml 配 置⽂件,同时也⼤⼤简化了项⽬的开发。 那么,问题来了,究竟是应该使⽤ xml 还是注解呢? 最佳实践: 1. 应⽤的基本配置⽤ xml,⽐如:数据源、资源⽂件等; 2. 业务开发⽤注解,⽐如:Service 中注⼊ bean 等;

2.3. Spring3.x 到 Spring4.x 再到 Spring5.x

从 Spring3.x 开始提供了 Java 配置⽅式,使⽤ Java 配置⽅式可以更好的理解你配置的 Bean,现在我 们就处于这个时代,并且 Spring4.x、Spring5.x 和 Spring Boot 都推荐使⽤ java 配置的⽅式。

3.Spring 5.X 应⽤零配置开发

Spring 框架从 5.x 版本推荐使⽤注解形式来对 java 应⽤程序进⾏开发与配置,并且可以完全替代原始 的 XML + 注解形式的开发,在使⽤注解形式进⾏项⽬开发与环境配置时,Spring 框架提供了针对环境配 置与业务 bean 开发相关注解。

3.1注解 3.1.1声明Bean注解
@Component: 组件 没有明确规定其角色,作用在类级别上声明当前类为一个组件,被Spring Ioc容器维护
@Service: 在业务逻辑层(Service层)类级别进行声明
@Repository:在数据访问层(dao层)类级别声明
@Controller: 在展现层(MVC)使用 标注当前类为一个控制器
3.1.2注入Bean注解
@AutoWried: Spring官方提供注解
@Inject: JSR-330 提供注解(标准制定方)
@Resource: JSR-250 提供注解

以上三种注解在 Set ⽅法或属性上声明,⼀般情况下通⽤⼀般开发中更习惯声明在属性上,代码简洁 清晰。基于5.x 注解配置⽅式简化了xml 配置,应⽤程序开发与xml 环境配置均通过相应注解来实现。

3.1.3.Spring5.x中配置与获取Bean注解
@Configuration: 作用与类上,将当前类声明为一个配置类,相当于一个xml配置文件
@ComponentScan: 自动扫描指定包下标注有@Repository,@Service,@Controller
@Component: 注解的类并由Ioc容器进行实例化和维护
@Bean: 作用于方法上,相当于xml文件中声明当前方法返回值为一个bean
@Value: 获取property文件指定key value值
3.2.实例1-IOC中Bean的实例化与获取 3.2.1.创建Spring普通工程

在pom.xml中添加坐标相关配置



 
 org.springframework
 spring-context
 5.2.4.RELEASE
 


 
 
 
 org.apache.maven.plugins
 maven-compiler-plugin
 2.3.2
 
 
 1.8
 
 1.8
 
 utf-8
 
 
 

3.2.2.创建Bean对象

UserDao.java

@Repository
public class UserDao{
    public void test(){
        System.out.println("UserDao.test...");
    }
}

UserService.java

@Service
public class UserService{
    @Resource
    private UserDao userdao;
    
    public void test(){
        System.out.println("UserService.test...");
        userDao.test();
    }
}
3.2.3.创建IocConfig配置类
//当前类声明为一个配置类
@Configuration
//设置扫描包范围
@ComponentScan("com.xxx.springboot")
public class IocConfig{}
3.2.4创建启动类执行测试
public class Starter{
    public static void main(String[] args){
        //基于Java的配置类加载Spring的应用上下文
        AnnotationConfigApplicationContext ac = new
 AnnotationConfigApplicationContext(IocConfig.class);
        //获取指定的Bean对象
        UserService userService = ac.getBean(UserService.class);
        //调用Bean对象的方法
        userService.test();
    }
}

此时启动SpringIOC容器,通过实例化 AnnotationConfigApplicationContext类,接受配置参数类IocConfig,并获取UserService Bean实现方法调用,此时应用环境不存在xml配置文件,简化了应用的xml配置.

3.3.实例2-@Bean注解使用

使用@Bean注解声明在方法(注意:方法名一般为bean对象)

3.3.1.创建Bean对象

AccountDao.java

//注意:此时类级别并未添加@Repository注解
public class AccountDao{
    public void test(){
        System.out.println("AccountDao.test...");
    }
}
3.3.2修改IocConfig配置类

添加返回AccountDao Bean对象方法

@Configuration
@ComponentScan("com.xxxx.springboot")
public class IocConfig02{
    //返回实例化的单例Bean对象
    @Bean
    public AccountDao accountDao(){
        return new AccountDao();
    }
}
3.3.3创建启动类并执行测试
public class Starter02 {
 public static void main(String[] args) {
 AnnotationConfigApplicationContext ac = new
AnnotationConfigApplicationContext(IocConfig.class);
 // 判断IocConfig对象是否是单例
 System.out.println(ac.isSingleton("IocConfig"));
 // 获取IocConfig对象
 IocConfig iocConfig = ac.getBean(IocConfig.class);
 
 // 获取AccountDao对象
 AccountDao accountDao01 = iocConfig.accountDao();
 AccountDao accountDao02 = iocConfig.accountDao();
 System.out.println(accountDao01 + "," + accountDao02);
 
 accountDao01.test();
 }
}
3.4.实例3-读取外部配置文件

在开发 Java web 应⽤时,配置⽂件是⽐较常⻅的,⽐如 xml,properties,yml 等⽂件,在 Spring 应 ⽤中对于配置⽂件的读取同样提供⽀持。对于配置⽂件读取,我们可以通过 @PropertySource 注解声明 到类级别来指定读取相关配置。

Spring El 表达式语⾔,⽀持在 Xml 和注解中使⽤表达式,类似于 JSP 中 EL 表达式,Spring 框架借助 该表达式实现资源注⼊,主要通过 @Value 注解来使⽤表达式,通过 @Value 注解,可以实现普通字符 串,表达式运算结果,Bean 属性⽂件内容,属性⽂件等参数注⼊。具体使⽤如下:

3.4.1.准备配置文件

src/main/resources ⽬录下添加 user.properties、jdbc.properties ⽂件

# user.properties
user.userName=admin
user.password=admin

#jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/hr?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
3.4.2.@PropertySource加载配置文件

通过@PropertySource加载property配置文件

@Configuration
@ComponentScan("com.xxxx")
@PropertySource(value={"classpath:jdbc.properties","classpath:user.properties"})
public class IocConfig03{
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String userName;
    @Value("{jdbc.password}")
    private String password;
    
    //控制台打印属性值信息
    public void showConfigInfo(){
         System.out.println("driver:" + driver + ",url:" + url);
         System.out.println("userName:" + userName + ",password:" + password);
    }
}
3.4.3.其他Bean对象获取properties文件内容
@Service
public class UserService{
    @Resource
    private UserDao userDao;
    
    @Value("${user.userName}")
    private String userName;
    @Value("{jdbc.password}")
    private String password;
    
    public void test(){
        System.out.println("UserService.test...");
        userDao.test();
        System.out.println("userName:" + userName + ",password:" + password);
    }
}

启动,查看控制台输出内容效果

3.5.组合注解与元注解

Spring 从2.x版本开始引⼊注解⽀持(⽬的是jdk1.5中推出注解功能),通过引⼊注解来消除⼤量xml 配 置,Spring 引⼊注解主要⽤来注⼊ bean 以及 aop 切⾯相关配置,但由于注解⼤量使⽤,就会造成⼤量 重复注解代码出现,代码出现了重复,Spring 为了消除重复注解,在元注解上引⼊了组合注解,其实可 以理解为对代码的重构,相当于注解的注解,拥有元注解的原始功能,⽐如在定义配置类时⽤到的 @Configuration 注解就是组合注解,拥有 @Component 注解功能,即配置类本身也是⼀个被 IOC 维护的 单例 Bean。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@documented
@Component
public @interface Configuration{}
3.5.1自定义组合注解

定义MyCompScan注解,拥有@ComponentScan扫描器注解功能

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Configuration
@ComponentScan
public @interface MyCompScan{
    String[] value() default{};
}
3.5.2.应用组合注解
@MyCompScan("com.xxxx.springboot")
@PropertySource(value = {"classpath:jdbc.properties","classpath:user.properties"})
public class IocConfig04 {
 
 @Value("${jdbc.driver}")
 private String driver;
 @Value("${jdbc.url}")
 private String url;
 @Value("${jdbc.username}")
 private String userName;
 @Value("${jdbc.password}")
 private String password;
 
 public void showConfigInfo(){
 System.out.println("driver:" + driver + ",url:" + url);
 System.out.println("userName:" + userName + ",password:" + password);
 }
}

测试组合注解

public class Starter {
 public static void main(String[] args) {
 AnnotationConfigApplicationContext ac = new
AnnotationConfigApplicationContext(IocConfig04.class);
 UserService userService = ac.getBean(UserService.class);
 userService.test(); 
 }
}
4.Spring MVC零配置创建与部署

基于Spring Mvc 5.x使用Maven搭建SpringMvc Web项目,通过Spring提供的注解与相关配置来对项目进行创建与部署.

4.1创建Spring MVC Web工程

创建Maven的Web项目

4.2pom.xml添加坐标相关配置

 org.springframework
 spring-web
 5.2.4.RELEASE



 org.springframework
 spring-webmvc
 5.2.4.RELEASE

!-- web servlet -->

 javax.servlet
 javax.servlet-api
 3.0.1


 springmvc
 
 
 
 org.apache.maven.plugins
 maven-compiler-plugin
 2.3.2
 
 1.8
 1.8
 utf-8
 
  
 

4.3添加源代码
@Controller
public class HelloController{
    @RequestMapping("/index")
    public String index(){
        return "index";
    }
}
4.4添加试图

在 WEB-INF/views ⽬录下创建 index.jsp(这⾥以jsp为模板)


 
 Hello mvc!
 

4.5.SpringMVC配置类添加

Spring Mvc 配置信息 MvcConfig ⽂件添加,作为 Mvc 框架环境,原来是通过 xml 来进⾏配置 (视图解析 器、Json转换器、⽂件上传解析器等),这⾥基于注解通过继承 WebMvcConfigurerAdapter 类并重写相关 ⽅法来进⾏配置 (注意通过 @EnableWebMvc 注解来启动 MVC 环境)。

// 配置类
@Configuration
// 在@Configuration注解的配置类中添加,⽤于为该应⽤添加SpringMVC的功能
@EnableWebMvc
// 扫描包范围
@ComponentScan("com.xxxx.springboot")
public class MvcConfig {
 
 @Bean // 将⽅法返回的结果交给IOC容器维护
 public InternalResourceViewResolver viewResolver(){
 // 获取视图解析器
 InternalResourceViewResolver viewResolver = new
InternalResourceViewResolver();
 // 设置前缀
 viewResolver.setPrefix("/WEB-INF/views/");
 // 设置后缀
 viewResolver.setSuffix(".jsp");
 // 返回解析器对象 (交给IOC容器进⾏维护)
 return viewResolver;
 }
}

MvcConfig 类定义好了,那么问题来了,怎么加载 MvcConfig 类呢,原来在构建 Mvc 应⽤时是通过容 器启动应⽤时加载 web.xml ⽂件实现配置⽂件加载,现在的环境 web.xml ⽂件不存在,此时基于注解⽅ 式构建的 Mvc 应⽤,定义 WebInitializer 实现 WebApplicationInitializer 接⼝ (该接⼝⽤来配置 Servlet3.0+ 配置的接⼝,⽤于替代 web.xml 配置),当 servlet 容器启动Mvc应⽤时会通过 SpringServletContainerInitializer 接⼝进⾏加载,从⽽加载 Mvc 应⽤信息配置。实现该接⼝ onStartup ⽅ 法 ,加载应⽤信息配置。

4.6.入口文件代码添加
public class WebInitializer implements WebApplicationInitializer {
 @Override
 public void onStartup(ServletContext servletContext) throws ServletException {
 // 基于Java的配置类加载Spring的应⽤上下⽂
 AnnotationConfigWebApplicationContext ctx = new
AnnotationConfigWebApplicationContext();
 // 注册 Mvc 配置信息
 ctx.register(MvcConfig.class);
 // 设置 ServletContext 上下⽂信息
 ctx.setServletContext(servletContext);
  // 配置转发器 Dispatcher
 ServletRegistration.Dynamic servlet =
servletContext.addServlet("dispatcher",new DispatcherServlet(ctx));
 // 设置映射路径
 servlet.addMapping("/");
 // 启动时即实例化 Bean
 servlet.setLoadOnStartup(1);
 }
}
// 静态资源 handler不进⾏处理 直接响应到客户端
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer
configurer) {
 configurer.enable();
}
// 配置拦截器
@Bean
public LoginInterceptor loginInterceptor(){
 return new LoginInterceptor();
}
// 添加拦截器到mvc 环境
@Override
public void addInterceptors(InterceptorRegistry registry) {
 registry.addInterceptor(loginInterceptor());
}

4.7.部署与测试

通过Tomcat启动项目并访问

当项⽬访问成功后,那么问题来了,如果项⽬中存在静态资源⽂件,Handler 放⾏处理该如何配置, 定义的拦截器怎么应⽤,此时关注 WebMvcConfigurationSupport ⽗类⽅法,重写相关⽅法即可。

// 静态资源 handler不进⾏处理 直接响应到客户端
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer
configurer) {
 configurer.enable();
}
// 配置拦截器
@Bean
public LoginInterceptor loginInterceptor(){
 return new LoginInterceptor();
}
// 添加拦截器到mvc 环境
@Override
public void addInterceptors(InterceptorRegistry registry) {
 registry.addInterceptor(loginInterceptor());
}
5.SpringBoot概念与特点 5.1.框架概念

随着动态语⾔流⾏(Ruby、Scala、NodeJs等),Java 开发变得相对笨重,配置繁琐,开发效率低下,部 署流程复杂,以及第三⽅集成难度也相对较⼤,针对该环境,Spring Boot 被开发出来,其使⽤“习惯⼤ 于配置⽬标”,借助Spring Boot 能够让项⽬快速运⾏起来,同时借助 Spring Boot 可以快速创建 web 应⽤ 并独⽴进⾏部署(jar包 war 包⽅式,内嵌 servlet 容器),同时借助 Spring Boot 在开发应⽤时可以不⽤或 很少去进⾏相关 xml 环境配置,简化了开发,⼤⼤提⾼项⽬开发效率。 Spring Boot 是由 Pivotal 团队提供的全新框架,其设计⽬的是⽤来简化 Spring 应⽤的初始搭建以及开 发过程。该框架使⽤了特定的⽅式来进⾏配置,从⽽使开发⼈员不再需要定义样板化的配置。通过这种 ⽅式,让 Spring Boot在蓬勃发展的快速应⽤开发领域 (rapid application development) 成为领导者。

5.2.框架特点

​ 创建独⽴ Spring 应⽤程序、嵌⼊式 Tomcat、Jetty 容器、⽆需部署 WAR 包、简化 Maven 及 Gradle 配 置、尽可能⾃动化配置 Spring、直接植⼊产品环境下的实⽤功能,⽐如度量指标、健康检查及扩展配 置、⽆需代码⽣成及 XML 配置等,同时 Spring Boot 不仅对 web 应⽤程序做了简化,还提供⼀系列的依 赖包来把其它⼀些⼯作做成开箱即⽤。

5.3.Spring Boot快速入门 5.3.1.环境准备: Idea,Maven,jdk 1.8+,Spring Boot 2.x 5.3.2.创建项目

通过Maven创建一个普通的java项目

5.3.3.添加依赖坐标

 org.springframework.boot
 spring-boot-starter-parent
 2.2.2.RELEASE


 
 org.springframework.boot
 spring-boot-starter-web
 

​ Spring Boot的项目必须将parent设置为Spring Boot 的parent,该parent包含了大量默认的配置,简化程序的开发.

5.3.4.导入Spring Boot的web坐标与相关插件

 org.springframework.boot
 spring-boot-maven-plugin

5.3.5. 添加源代码
@Controller
public class HelloController {
 @RequestMapping("hello")
 @ResponseBody
 public String hello(){
 return "Hello SpringBoot";
 }
}
5.3.6.创建启动程序

在 HelloController.java 所在包下,创建 StarterApplication.java

@SpringBootApplication
public class Starter{
 public static void main(String[] args) {
 SpringApplication.run(Starter.class);
 }
}
5.3.7.启动Spring Boot应用并测试

这里运行main方法即可,通过浏览器访问http://localhost:8080/hello

6.Spring Boot核心配置 6.1.设置Banner图标

​ 在搭建 Spring Boot 项⽬环境时,程序启动后会在控制台打印醒⽬的 SpringBoot 图标,图标描述了 Spring Boot 版本信息,这是 Spring Boot 项⽬与 Spring 项⽬启动区别较⼤的地⽅,Spring Boot 通过默认 Banner 在程序启动时显示应⽤启动图标,当然图标我们也可以进⾏⾃定义。

6.1.1.Banner图标自定义

​ Spring Boot 项⽬启动时默认加载 src/main/resources ⽬录下的 banner.txt 图标⽂件,如果该⽬录⽂件未 提供,则使⽤ Spring Boot 默认。在 main ⽬录下新建 resources 资源⽬录,并在该⽬录下新建banner.txt ⽂本⽂件,可以设置⾃定义图标。 打开⽹址: http://patorjk.com/software/taag/#p=display&f=Graffiti&t=Type%20Something

对应⽂本并将⽂本内容copy 到 banner.txt 中

6.1.2.Banner图标关闭

​ 如果启动时不想要看到启动图标 ,这⾥也可以通过代码进⾏关闭 *** 作,修改 StarterApplication 设置 BannerMode 值为 Banner.Mode.OFF,启动 Spring Boot 应⽤关闭图标输出功能即可

@SpringBootApplication
public class StarterApplication {
 public static void main(String[] args) {
 SpringApplication springApplication = new SpringApplication(StarterApplication
.class);
 // 设置 banner 图标关闭
 springApplication.setBannerMode(Banner.Mode.OFF);
 springApplication.run();
 }
}
6.2.Spring Boot配置文件

​ Spring Boot 默认会读取全局配置⽂件,配置⽂件名固定为:application.properties 或 application.yml, 放置在 src/main/resources 资源⽬录下,使⽤配置⽂件来修改 SpringBoot ⾃动配置的默认值。 在 resources 资源⽬录下添加 application.properties ⽂件,配置信息如下:

## 项⽬启动端⼝号配置
server.port=8989
## 项⽬访问上下⽂路径
server.servlet.context-path=/mvc
## 数据源配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/hr?
useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
6.3.Start坐标&自动化配置 6.3.1Start坐标配置

​ Spring Boot 引⼊了全新的Starter坐标体系,简化企业项⽬开发⼤部分场景的 Starter pom,应⽤程序引 ⼊指定场景的 Start pom 相关配置就可以消除 ,通过 Spring Boot 就可以得到⾃动配置的 Bean。

6.3.1.1.Web starter

使用Spring MVC 来构建RESTful Web应用,并使用Tomcat作为默认内嵌容器


 org.springframework.boot
 spring-boot-starter-web

6.3.1.2.Freemarker Starter & Thymeleaf starter

集成试图技术,引入Freemarker Starter,Thymeleaf Starter


 org.springframework.boot
 spring-boot-starter-freemarker


 org.springframework.boot
 spring-boot-starter-thymeleaf

6.3.1.3.JavaMail邮件发送Starter

 org.springframework.boot
 spring-boot-starter-mail

6.3.1.4.引入AOP环境

 org.springframework.boot
 spring-boot-starter-aop

相关starter系列坐标参考

名称 						      描述
spring-boot-starter          核⼼Spring Boot starter,包括⾃动配置⽀持,⽇志和YAML
spring-boot-starteractuator    ⽣产准备的特性,⽤于帮我们监控和管理应⽤
spring-boot-starter-amqp     对”⾼级消息队列协议”的⽀持,通过spring-rabbit实现
spring-boot-starter-aop      对⾯向切⾯编程的⽀持,包括spring-aop和AspectJ
spring-boot-starter-batch     对Spring Batch的⽀持,包括HSQLDB数据库
spring-boot-startercloud-connectors    对Spring Cloud Connectors的⽀持,简化在云平台下(例如,CloudFoundry 和Heroku)服务的连接
spring-boot-starter-dataelasticsearch  对Elasticsearch搜索和分析引擎的⽀持,包括spring-data-elasticsearch
spring-boot-starter-datagemfire  对GemFire分布式数据存储的⽀持,包括spring-data-gemfire
spring-boot-starter-datajpa      对”Java持久化API”的⽀持,包括spring-data-jpa,
spring-boot-starter-datmongodb 对MongoDB NOSQL数据库的⽀持,包括spring-data-mongodb
spring-boot-starter-datarest   对通过REST暴露Spring Data仓库的⽀持,通过spring-data-restwebmvc实现
spring-boot-starter-datasolr    对Apache Solr搜索平台的⽀持,包括spring-data-solr
spring-boot-starterfreemarker    对FreeMarker模板引擎的⽀持
spring-boot-startergroovy-templates  对Groovy模板引擎的⽀持
spring-boot-starterhateoas     对基于HATEOAS的RESTful服务的⽀持,通过spring-hateoas实现
spring-boot-starterhornetq     对”Java消息服务API”的⽀持,通过HornetQ实现
spring-boot-starterintegration   对普通spring-integration模块的⽀持
spring-boot-starter-jdbc         对JDBC数据库的⽀持
spring-boot-starter-jersey       对Jersey RESTful Web服务框架的⽀持
spring-boot-starter-jtaatomikos 对JTA分布式事务的⽀持,通过Atomikos实现
spring-boot-starter-jtabitronix 对JTA分布式事务的⽀持,通过Bitronix实现
spring-boot-starter-mail         对javax.mail的⽀持
spring-boot-startermobile       对spring-mobile的⽀持
spring-boot-startermustache     对Mustache模板引擎的⽀持
spring-boot-starter-redis        对REDIS键值数据存储的⽀持,包括spring-redis
spring-boot-startersecurity      对spring-security的⽀持
spring-boot-startersocial-facebook 对spring-social-facebook的⽀持
spring-boot-startersocial-linkedin 对spring-social-linkedin的⽀持
spring-boot-startersocial-twitter 对spring-social-twitter的⽀持
spring-boot-starter-test 对常⽤测试依赖的⽀持,包括JUnit, Hamcrest和Mockito,还有springtest模块
spring-boot-starterthymeleaf    对Thymeleaf模板引擎的⽀持,包括和Spring的集成
spring-boot-startervelocity     对Velocity模板引擎的⽀持
spring-boot-starter-web          对全栈web开发的⽀持, 包括Tomcat和spring-webmvc
spring-boot-starterwebsocket    对WebSocket开发的⽀持
spring-boot-starter-ws            对Spring Web服务的⽀持

传统的 maven 坐标这⾥同样适⽤,如果引⼊传统 maven 坐标需要考虑相关配置类的编写。

如果引⼊相关starter坐标这⾥不存在,可以到这⾥搜索。

6.3.2.自动化配置

6.3.2.1. SpringBoot Starter坐标版本查看

前⾯介绍了 SpringBoot Starter 相关坐标,引⼊ Starter 坐标来简化应⽤环境的配置。这⾥以环境搭建 spring-boot-starter-web 坐标来简单分析 SpringBoot ⾃动化配置过程。


 org.springframework.boot
 spring-boot-starter-web

这⾥引⼊的 web 环境坐标不像传统的maven坐标那样包含坐标的版本号,项⽬中引⼊的 starter 系列坐 标对应的版本库统⼀由⽗⼯程坐标统⼀控制即项⽬中引⼊的 parent 标签。


 org.springframework.boot
 spring-boot-starter-parent
  
 2.2.2.RELEASE

这⾥ spring-boot-starter-parent 继承 spring-boot-dependencies 项⽬,在 spring-boot-dependencies 项⽬ 中定义了 spring-boot-starter-web 坐标的版本!(spring-boot-dependencies 项⽬中定义了当前 SpringBoot版本下各个 starter 坐标版本以及依赖的其他坐标版本)

这⾥依赖的坐标较多,不在截图展示,可关注 spring-boot-dependencies-2.2.2.RELEASE.pom ⽂件。

6.3.2.2.Spring Boot自动化配置

Spring Boot项目一般都会有Application的入口类,入口类中提供main方法,这是一个标准的Java应用程序的入口方法.@SpringBootApplication注解是Spring Boot的核心注解,它其实是一个组合注解:

可以看出该注解也是⼀个组合注解,组合了 @Configuration 注解,对于Spring Boot应⽤, @SpringBootConfiguration 注解属于Boot 项⽬的配置注解也是属于⼀个组合注解,Spring Boot 项⽬中推 荐使⽤@SpringBootConfiguration 注解,因为其组合了 @Configuration 注解。

​ @EnableAutoConfiguration 注解组合了 @AutoConfigurationPackage、 @import(AutoConfigurationimportSelector.class) 注解。 @AutoConfigurationPackage 底层也是⼀个 @import(AutoConfigurationPackages.Registrar.class),其会把 启动类的包下组件都扫描到Spring容器中。

​ @import(AutoConfigurationimportSelector.class) ⾃动配置的核⼼类 AutoConfigurationimportSelector.class,该类导⼊⼤量的⾃动配置类,debug可以发现,其读取的是 classpath下的 meta-INF/spring.factories 下配置⽂件。

​ 以 WebMvcAutoConfiguration 为例,可以看出该类使⽤ @Configuration 注解进⾏标注其为⼀个配置 类。

​ 当然 spring.factories ⽂件中配置类默认不会都⽣效,具体哪些配置类⽣效由配置类上标注的 @ConditionalOnClass 注解来决定,这⾥了解下 @ConditionalOnClass 注解含义。

@ConditionalOnBean // 当给定的在bean存在时,则实例化当前Bean
@ConditionalOnMissingBean // 当给定的在bean不存在时,则实例化当前Bean
@ConditionalOnClass // 当给定的类名在类路径上存在,则实例化当前Bean
@ConditionalOnMissingClass // 当给定的类名在类路径上不存在,则实例化当前Bean

意味着 WebMvcAutoConfiguration 配置类⽣效需要环境中存在 Servlet.class,DispatcherServlet.class, WebMvcConfigurer.class 实例,配置类才会⽣效。

从以上分析可以得出如下结论:

Spring Boot 通过 maven 中的 starter 导⼊了所需场景下的 jar 包,并通过主启动类上的 @SpringBootApplication 中的 @EnableAutoConfiguration 读取了类路径下的 metaINF/spring.factories下 EnableAutoConfiguration 的配置类,这些配置类使⽤ @ConditionalOnClass 来标注,根据@ConditionalOnClass 标注的约束条件来引⼊⾃动化的环境配 置

6.4.Profile配置

Profile 是 Spring ⽤来针对不同环境对不同配置提供⽀持的全局 Profile 配置使⽤ application- {profile}.yml,⽐如 application-dev.yml ,application-test.yml。 通过在 application.yml 中设置 spring.profiles.active=test|dev|prod 来动态切换不同环境,具体配置如下:

application-dev.yml开发环境配置文件

sever:
  port:8989

application-test.yml测试环境配置文件

server:
	port:9999

application-prod.yml生产环境配置文件

server:
	port:8686

application.yml主配置文件

## 环境选择配置
spring:
	profiles:
	active:dev

启动Starter再次查看控制台输入效果

6.5.日志配置

​ 在开发企业项⽬时,⽇志的输出对于系统 bug 定位⽆疑是⼀种⽐较有效的⽅式,也是项⽬后续进⼊⽣ 产环境后快速发现错误解决错误的⼀种有效⼿段,所以⽇志的使⽤对于项⽬也是⽐较重要的⼀块功能。

​ Spring Boot 默认使⽤ LogBack ⽇志系统,如果不需要更改为其他⽇志系统如 Log4j2 等,则⽆需多余的 配置,LogBack 默认将⽇志打印到控制台上。如果要使⽤ LogBack,原则上是需要添加 dependency 依赖 的。


 org.springframework.boot
 spring-boot-starter-logging

因为新建的Spring Boot项目一般都会引用Spring-boot-starter或者spring-boot-starter-web,而这两个起步依赖中都已经包含了对于spring-boot-starter-logging的依赖,所以,无需额外添加依赖.

6.5.1.项目中日志信息输出

Starter启动类中添加Log日志类,控制台打印日志信息.

package com.xxxx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Starter {
 private static Logger logger = LoggerFactory.getLogger(Starter.class);
 public static void main(String[] args) {
 logger.info("SpringBoot 应⽤开始启动...");
 SpringApplication.run(Starter.class);
 }
6.5.2.日志输出格式配置

修改application.yml文件添加日志输出格式信息配置,可以修改application.yml文件来控制控制台日志输出格式,同时可以设置日志信息输出到外部文件.

logging:
 pattern:
 console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger- %msg%n"
 level: debug
 file:
 path: "."
 name: "springboot.log"
7.Freemarker&Thymeleaf视图集成 7.1.Freemarker视图集成

​ SpringBoot 内部⽀持 Freemarker 视图技术的集成,并提供了⾃动化配置类 FreeMarkerAutoConfiguration,借助⾃动化配置可以很⽅便的集成 Freemarker基础到 SpringBoot 环境 中。这⾥借助⼊⻔项⽬引⼊ Freemarker 环境配置。

Starter坐标引入


 org.springframework.boot
 spring-boot-starter-freemarker

添加 Freemarker 配置信息

Freemarker 默认默认视图路径⽂ resources/templates ⽬录(由⾃动化配置类 FreemarkerProperties 决定),该⽬录可以进⾏在 application.yml 中进⾏修改。

修改 application.yml 添加 freemarker 基本配置如下:

spring:
 freemarker:
 suffix: .ftl
 content-type: text/html
 charset: UTF-8
 template-loader-path: classpath:/views/

编写IndexController 控制器转发视图

package com.xxxx.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
 @RequestMapping("index")
 public String index(){
 return "index";
 }
}

views ⽬录下添加 index.ftl 视图

启动Starter访问

7.2.Thymeleaf视图集成

SpringBoot 支持多种视图技术集成,并且SpringBoot官网推荐使用Thymeleaf作为前端视图页面,这里实现Thymeleaf视图集成,借助入门项目引入Thymeleaf环境配置.

starter坐标引入


 org.springframework.boot
 spring-boot-starter-thymeleaf

添加Thymeleaf配置信息

​ Thymeleaf 默认默认视图路径 resources/templates ⽬录(由⾃动化配置类 ThymeleafProperties 类 决定),该⽬录可以进⾏在 application.yml 中进⾏修改

## 环境选择配置
spring:
 thymeleaf:
 prefix: classpath:/html/
 ## 关闭 thymeleaf ⻚⾯缓存
 cache: false

编写IndexController控制器转发视图

@Controller
public class IndexController {
 @RequestMapping("index")
 public String index(Model model){
 // 设置请求域的值
 model.addAttribute("msg","Hello SpringBoot");
 return "index";
 }
}

html ⽬录下添加 index.html 视图

修改 Thymeleaf 模板默认存放路径 (在 resources ⽬录下创建 html ⽂件夹)




 
 Thymeleaf视图


 
 


启动start访问

8.SpringBoot静态资源访问

从入门项目中可以看到:对于Spring Mvc请求拦截规则为’/’,Spring Boot 默认静态资源路径如下:略

即:我们可以在 resources 资源⽬录下存放 web 应⽤静态资源⽂件。

8.1.默认静态资源路径

在 resources ⽬录下创建 static 或者 public ⽬录,存放 images、js、css 等静态资源⽂件

8.2. ⾃定义静态资源路径

在 spring.resources.static-locations 后⾯追加⼀个配置 classpath:/os/

spring:
 # 修改默认的静态寻址资源⽬录 多个路径之间⽤逗号隔开
 resources:
 static-locations: classpath:/public/,classpath:/static/,classpath:/os/
9.SpringBoot 应⽤打包与部署

当项⽬开发完毕进⾏部署上线时,需要对项⽬进⾏打包 *** 作,⼊⻔中构建的项⽬属于普通应⽤,由于 SpringBoot 内嵌 Tomcat 容器,所有打包后的 jar 包默认可以⾃⾏运⾏。

9.1Jar包部署 9.1.1.配置打包命令

idea 下配置 clean compile package -Dmaven.test.skip=true 执⾏打包命令,target ⽬录得到 待部署的项⽬⽂件。

9.1.2.部署并访问

打开本地dos窗口,执行java-jar命令 部署已打好的jar包文件.

命令如下:java -jar jar包所在目录

9.2.war包部署

War 包形式部署 Web 项⽬在⽣产环境中是⽐较常⻅的部署⽅式,也是⽬前⼤多数 web 应⽤部署的⽅ 案,这⾥对于 Spring Boot Web 项⽬进⾏打包部署步骤如下

9.2.1.pom.xml修改

应用类型修改

由于入门项目构建的项目默认为jar应用,所以这里打war需要做如下修改

com.xxxx
springboot03
1.0-SNAPSHOT
war

内嵌tomcat忽略

构建 SpringBoot 应⽤时,引⼊的 spring-boot-starter-web 默认引⼊ Tomcat 容器,这⾥忽略掉内容 Tomcat


 org.springframework.boot
 spring-boot-starter-tomcat
 provided

 
  
 springboot
 
 
 org.springframework.boot
 spring-boot-maven-plugin
 
 
9.2.2.Starter修改

​ 添加容器启动加载⽂件 (类似于读取 web.xml),这⾥通过继承 SpringBootServletInitializer 类并重写 configure ⽅法来实现,在部署项⽬时指定外部 Tomcat 读取项⽬⼊⼝⽅法。

@SpringBootApplication
public class Starter extends SpringBootServletInitializer {
 private static Logger logger = LoggerFactory.getLogger(Starter.class);
 public static void main(String[] args) {
 logger.info("SpringBoot 应⽤开始启动...");
 SpringApplication.run(Starter.class);
 }
 @Override
 protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
 return builder.sources(Starter.class);
 }
}
9.2.3.打包 *** 作

执⾏命令,⽣成对应的 war 包

9.2.4.部署并访问

外部tomcat部署并访问

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5636640.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存