SpringBoot in Action——自定义配置

本文介绍如何利用SpringBoot的自动配置简化开发流程,包括如何覆盖自动配置、保护应用程序安全、微调自动配置的Bean属性,以及如何通过属性文件进行外置配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在传统的Spring配置的过程,就如同订比萨的时候自己指定全部的辅料。而Spring Boot自动配置就像是从菜单上选一份特色比萨,让Spring Boot处理各种细节比自己声明上下文里全部的Bean要容易很多。
幸运的是,Spring Boot自动配置非常灵活。就像比萨厨师可以不在你的比萨里放蘑菇,而是加墨西哥胡椒一样,Spring Boot能让你参与进来,影响自动配置的实施。

覆盖Spring boot自动配置

大多数情况下,自动配置的Bean刚好能满足你的需要,不需要去覆盖它们。但某些情况下,Spring Boot在自动配置时还不能很好地进行推断。

保护应用程序
Spring Boot自动配置让应用程序的安全工作变得易如反掌,你要做的只是添加Security起步依赖。以Gradle为例,应添加如下依赖:
compile("org.springframework.boot:spring-boot-starter-security")
如果使用Maven,那么你要在项目的<dependencies>块中加入如下

<dependency><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

这样就搞定了!重新构建应用程序后运行即可,现在这就是一个安全的Web应用程序了!

对比下,我们之前配置一堆,还运行出错?是不是轻松很多。

然而!我们的密码呢?帐号呢?
我们看到运行后的页面是这样的:
在这里插入图片描述
我特么怎么知道帐号密码呢?
此处的用户名是user,密码就有点麻烦了。密码是在应用程序每次运行时随机生成后写入日志的,你需要查找日志消息(默认写入标准输出),找到此类内容。

因此,我们会希望修改Spring Security的一些配置,至少!我们希望有一个好看一些的登录页面。还要有一个基于数据库或LDAP用户存储的身份验证服务。

创建自定义的安全配置
覆盖自动配置很简单,就当自动配置不存在,直接显式地写一段配置。

package com.leesanghyuk.web;

import com.leesanghyuk.data.ReaderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private ReaderRepository readerRepository;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http
                .authorizeRequests()
                .antMatchers("/").access("hasRole('ROLE_READER')") //必须有reader的角色
                .antMatchers("/**").permitAll()
                .and()
                .formLogin()
                .loginPage("/login") //登录表单的路径
                .failureUrl("/login?error=true");//登录失败路径

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
        auth.userDetailsService(new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                return readerRepository.findOne(username);
            }
        });
    }
}

Spring Security为身份认证提供了众多选项,后端可以是JDBC(Java Database Connectivity)、LDAP和内存用户存储。在这个应用程序中,我们会通过JPA用数据库来存储用户信息。

package com.leesanghyuk.data;

import com.leesanghyuk.domain.Reader;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ReaderRepository extends JpaRepository<Reader, String> {
}

和BookRepository类似,你无需自己实现ReaderRepository。这是因为它扩展了JpaRepository,Spring Data JPA会在运行时自动创建它的实现。这为你提供了18个操作Reader实体的方法。
说到Reader实体,Reader类就是最后一块拼图了,它就是一个简单的JPA实体,其中有几个字段用来存储用户名、密码和用户全名。

package com.leesanghyuk.domain;


import java.util.Arrays;
import java.util.Collection;

import javax.persistence.Entity;
import javax.persistence.Id;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

@Entity
public class Reader implements UserDetails {

    private static final long serialVersionUID = 1241887194095689628L;

    @Id
    private String username;

    private String fullname;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getFullname() {
        return fullname;
    }

    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Arrays.asList(new SimpleGrantedAuthority("ROLE_READER"));
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}

如你所见,Reader用了@Entity注解,所以这是一个JPA实体。此外,它的username字段上有@Id注解,表明这是实体的ID。这个选择无可厚非,因为username应该能唯一标识一个Reader。

通过属性文件外置配置

在处理应用安全时,你当然会希望完全掌控所有配置。不过,为了微调一些细节,比如改改端口号和日志级别,便放弃自动配置,这就有点得不偿失了。
事实上,Spring Boot自动配置的Bean提供了300多个用于微调的属性。当你调整设置时,只要在环境变量、Java系统属性、JNDI(Java Naming and Directory Interface)、命令行参数或者属性文件里进行指定就好了。

自动配置微调


禁用模版缓存:
如果阅读列表应用程序经过了几番修改,你一定已经注意到了,除非重启应用程序,否则对Thymeleaf模板的变更是不会生效的。这是因为Thymeleaf模板默认缓存。这有助于改善应用程序的性能,因为模板只需编译一次,但在开发过程中就不能实时看到变更的效果了。
将spring.thymeleaf.cache设置为false就能禁用Thymeleaf模板缓存。
在命令行里运行应用程序时,将其设置为命令行参数即可:(一次性)
$ java -jar readinglist-0.0.1-SNAPSHOT.jar --spring.thymeleaf.cache=false
或者,如果你希望每次运行时都禁用缓存,可以创建一个application.yml,包含以下内容:

spring:
	thymeleaf:
		cache: false

或者放在application.properties中:
spring.thymeleaf.cache=false


配置嵌入式服务器:
从命令行(或者Spring Tool Suite)运行Spring Boot应用程序时,应用程序会启动一个嵌入式的服务器(默认是Tomcat),监听8080端口。大部分情况下这样挺好,但同时运行多个应用程序可能会有问题。要是所有应用程序都试着让Tomcat服务器监听同一个端口,在启动第二个应用程序时就会有冲突。
但如果希望端口变更时间更长一点,可以在其他支持的配置位置上设置server.port。例如,把它放在应用程序Classpath根目录的application.yml文件里:

server:
	port: 8000

或者properties:server.port=8000


配置日志:
默认情况下,Spring Boot会用Logback(http://logback.qos.ch)来记录日志,并用INFO级别输出到控制台。在运行应用程序和其他例子时,你应该已经看到很多INFO级别的日志了。
我们可能希望使用log4j或者Log4j2,
那么你只需要修改依赖,引入对应该日志实现的起步依赖,同时排除掉Logback。

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter</artifactId>
	<exclusions>
		<exclusion>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-logging</artifactId>
		</exclusion>
	</exclusions>
</dependency>

或者使用gradle:

configurations {
	all*.exclude group:'org.springframework.boot',
			module:'spring-boot-starter-logging'
}

排除默认日志的起步依赖后,就可以引入你想用的日志实现的起步依赖了。在Maven里可以这样添加Log4j:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-log4j</artifactId>
</dependency>

或者compile("org.springframework.boot:spring-boot-starter-log4j")
要完全掌握日志配置,可以在Classpath的根目录(src/main/resources)里创建logback.xml文件。下面是一个logback.xml的简单例子:

<configuration>
	<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
		<encoder>
			<pattern>
				%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
			</pattern>
		</encoder>
	</appender>
	<logger name="root" level="INFO"/>
	<root level="INFO">
		<appender-ref ref="STDOUT" />
	</root>
</configuration>

除了日志格式之外,这个Logback配置和不加logback.xml文件的默认配置差不多。但是,通过编辑logback.xml,你可以完全掌控应用程序的日志文件。哪些配置应该放进logback.xml这个话题不在本书的讨论范围内,请参考Logback的文档以了解更多信息。

即使如此,你对日志配置最常做的改动就是修改日志级别和指定日志输出的文件。使用了Spring Boot的配置属性后,你可以在不创建logback.xml文件的情况下修改那些配置。
要设置日志级别,你可以创建以logging.level开头的属性,后面是要日志名称。如果根日志级别要设置为WARN,但Spring Security的日志要用DEBUG级别,可以在application.yml里加入以下内容:

logging:
	level:
		root: WARN
		org:
			springframework:
				security: DEBUG

具体怎么设置,用到再说。


配置数据源:
虽然你可以显式配置自己的DataSource Bean,但通常并不用这么做,只需简单地通过属性配置数据库的URL和身份信息就可以了。
在applicaiton.properties中加入:

spring.datasource.url=jsbc:mysql://localhost/readingList
spring.datasource.username=root
spring.datasource.password=root

通常你都无需指定JDBC驱动,Spring Boot会根据数据库URL识别出需要的驱动,但如果识别出问题了,你还可以设置spring.datasource.driver-class-name属性:

spring.datasource.url=jsbc:mysql://localhost/readingList
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

也可以配置连接池。
除此之外,配置profile,spring.profiles.active=production之类的。我们不做赘述了。

定制应用程序错误页面

SpringBoot它的自动配置会默认查找一个名为error的视图,如果找不到会默认使用它自己的视图。

Summary A developer-focused guide to writing applications using Spring Boot. You'll learn how to bypass the tedious configuration steps so that you can concentrate on your application's behavior. Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications. About the Technology The Spring Framework simplifies enterprise Java development, but it does require lots of tedious configuration work. Spring Boot radically streamlines spinning up a Spring application. You get automatic configuration and a model with established conventions for build-time and runtime dependencies. You also get a handy command-line interface you can use to write scripts in Groovy. Developers who use Spring Boot often say that they can't imagine going back to hand configuring their applications. About the Book Spring Boot in Action is a developer-focused guide to writing applications using Spring Boot. In it, you'll learn how to bypass configuration steps so you can focus on your application's behavior. Spring expert Craig Walls uses interesting and practical examples to teach you both how to use the default settings effectively and how to override and customize Spring Boot for your unique environment. Along the way, you'll pick up insights from Craig's years of Spring development experience. What's Inside Develop Spring apps more efficiently Minimal to no configuration Runtime metrics with the Actuator Covers Spring Boot 1.3 About the Reader Written for readers familiar with the Spring Framework. About the Author Craig Walls is a software developer, author of the popular book Spring in Action, Fourth Edition, and a frequent speaker at conferences.
Spring.Boot.in.Action.2015.12.pdfFor online information and ordering of this and other manning books, please visit www.manning.com.thepublisheroffersdiscountsonthisbookwhenorderedinquantity For more information, please contact Special sales department Manning publications co 20 Baldwin Road PO BoX 761 Shelter island. ny11964 Emailorders@manning.com @2016 by manning Publications Co. All rights reserved No part of this publication may be reproduced, stored in a retrieval system, or transmitted,in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and manning Publications was aware of a trademark claim, the designations have been printed in initial caps ll Recognizing the importance of preserving what has been written, it is Mannings policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine Manning publications co Development editor: Cynthia Kane 20 Baldwin Road Technical development editor: Robert casazza PO BoX 761 Copyeditor: Andy Carroll Shelter island. ny11964 Proofreader: Corbin Collins Technical p der John Guthrie Typesetter: Gordan Salinovic Cover designer: Marija Tudor ISBN9781617292545 Printed in the united states of america 12345678910-EBM-201918171615 contents reword vii pre eface 2x about this book xii acknowledgments xu Bootstarting Spring I 1. 1 Spring rebooted Taking a fresh look at spring 2. Examining spring Boot essentials 4 What Spring Boot isn't 7 1.2 Getting started with Spring boot 8 Installing the spring boot cli 8 Initializing a spring boot project with Spring Initializr 12 3 Summary 22 Developing your first Spring Boot application 23 2.1 Putting spring boot to work 24 Examining a newly initialized spring boot project 26 Dissecting Bc iect build 30 2.2 USing starter dependencies 33 Specifying facet-based dependencies 34. Overriding starter transitive dependencies 35 CONTENTS 2.8 USing automatic configuration 37 Focusing on application functionality 37. Running the application 45. What just happened? 45 2.4 Summary 48 Customizing configuration 49 8.1 Overriding Spring Boot auto-configuration 50 Securing the application 50. Creating a custom security configuration 51. Taking another peek under the covers of auto-configuration55 8.2 Externalizing configuration with properties 57 Fine-tuning auto-configuration 58. Externally configuring application beans 64. Configuring with profiles 69 8.8 Customizing application error pages 71 3.4 Summary 74 Testing with Spring Boot 76 4.1 Integration testing auto-configuration 77 4.2 Testing web applications 79 Mocking spring MvC 80- Testing web security 83 4.3 Testing a running application 86 Starting the server on a random port 87. Testing HTML pages with selenium 88 4.4 Summary 90 Getting Groovy with the spring Boot CLI 92 5.1 Developing a Spring Boot CLI application 93 Setting up the cli project 93 Eliminating code noise with Groovy 94. What just happened? 98 5.2 Grabbing dependencies 100 Overriding default dependency versions 101. Adding dependency repositories 102 5.8 Running tests with the CLI 102 5.4 Creating a deployable artifact 105 5.5 Summary 106 CONTENTS 6 Applying Grails in Spring Boot 107 1 Using gorm for data persistence 108 2 Defining views with groovy server pages 113 6.3 Mixing spring boot with grails 3 115 Creating a new grails project 116 Defining the domain 118 Writing a grails controller 119. Creating the view 120 6.4 Summary 123 Taking a peek inside with the Actuator 124 7.1 Exploring the actuator's endpoints 125 Viewing configuration details 126. Tapping runtime metrics 133 Shutting down the application 139. Fetching application information 140 7.2 Connecting to the Actuator remote shell 141 Viewing the autoconfig report 142. Listing application beans 143 Watching application metrics 144.Invoking actuator endpoints 145 7. 3 Monitoring your application with JMX 146 7.4 Customizing the Actuator 148 Changing endpoint Ds 148 Enabling and disabling endpoints 149 Adding custom metrics and gauges 149- Creating a custom trace repository 153 Plugging in custom health indicators 155 7.5 Securing Actuator endpoints 156 7.6 Summary 159 8 Deploying Spring Boot applications 160 8.1 Weighing deployment options 161 8.2 Deploying to an application server 162 Building a WaRfile 162 Creating a production profile Enabling database migration 168 8.3 Pushing to the cloud 173 Deploying to Cloud Foundry 173 Deploying to Heroku 177 8. Summary 180 appendix a spring Boot developer Tools 187 appendix b spring Boot starters 188 appendix c Configuration properties 195 appendix d spring boot dependencies 232 index 243 In the spring of 2014, the Delivery Engineering team at Netflix set out to achieve a lofty goal: enable end-to-end global continuous delivery via a software platform that facilitates both extensibility and resiliency. my team had previously built two different applications attempting to address Netflix's delivery and deployment needs, but both were beginning to show the telltale signs of monolith-ness and neither met the goals of flexibility and resiliency. What's more, the most stymieing effect of these monolithic applications was ultimately that we were unable to keep pace with our partner's inno- vation. Users had begun to move around our tools rather than with them It became apparent that if we wanted to provide real value to the company and rap- idly innovate, we needed to break up the monoliths into small, independent services that could be released at will. Embracing a microservice architecture gave us hope that we could also address the twin goals of flexibility and resiliency. but we needed to do it on a credible foundation where we could count on real concurrency, legitimate moni- toring, reliable and easy service discovery, and great runtime performance With the jVM as our bedrock, we looked for a framework that would give us rapid velocity and steadfast operationalization out of the box. We zeroed in on Spring Boot Spring Boot makes it effortless to create Spring-powered, production-ready ser- vices without a lot of code! Indeed, the fact that a simple Spring Boot Hello World application can fit into a tweet is a radical departure from what the same functionality required on the vm only a few short years ago. Out-of-the-box nonfunctional features like security, metrics, health-checks, embedded servers, and externalized configura tion made boot an easy choice for us FOREWORD Yet, when we embarked on our Spring boot journey solid documentation was hard to come by. Relying on source code isnt the most joyful manner of figuring out how to properly leverage a frameworks features It's not surprising to see the author of mannings venerable Spring in Action take on the challenge of concisely distilling the core aspects of working with Spring Boot into another cogent book. Nor is it surprising that Craig and the Manning crew have done another tremendously wonderful job! Spring Boot in Action is an easily readable book, as weve now come to expect from Craig and manning From chapter Is attention-getting introduction to Boot and the now legend ary 9Oish-character tweetable Boot application to an in-depth analysis of Boots Actuator in chapter 7, which enables a host of auto-magical operational features required for any production application, Spring Boot in Action leaves no stone unturned. Indeed, for me, chapter 7's deep dive into the Actuator answered some of the lingering questions I've had in the back of my head since picking up Boot well over a year ago. Chapter 8s thor- ough examination of deployment options opened my eyes to the simplicity of cloud Foundry for cloud deployments. One of my favorite chapters is chapter 4, where Craig explores the many powerful options for easily testing a Boot application. From the get- o, I was pleasantly surprised with some of Springs testing features, and boot takes g advantage of them nicely As I've publicly stated before, Spring Boot is just the kind of framework the Java community has been seeking for over a decade. Its easy-to-use development features and out-of-the-box operationalization make java development fun again I,m pleased to report that Spring and spring boot are the foundation of Netflix's new continuous delivery platform. What's more, other teams at Netflix are following the same path because they too see the myriad benefits of boot It's with equal parts excitement and passion that I absolutely endorse craigs book as the easy-to-digest and fun-to-read Spring boot documentation the Java community has been waiting for since Boot took the community by storm. Craigs accessible writ- ing style and sweeping analysis of boot's core features and functionality will surely leave readers with a solid grasp of Boot(along with a joyful sense of awe for it) Keep up the great work Craig Manning Publications, and all the brilliant develop ers who have made spring boot what it is today each one of you has ensured a bright future for the JV ANDREW GLOVER MANAGER, DELIVERY ENGINEERING AT NETFLIX preface At the 1964 New York World's Fair, Walt Disney introduced three groundbreaking attractions:"“it' s a small world,”“ Great Moments with mr. Lincoln," and the“ Carouse of Progress " All three of these attractions have since moved into disneyland and walt Disney world, and you can still see them today My favorite of these is the Carousel of Progress. Supposedly, it was one of Walt Disneys favorites too. It's part ride and part stage show where the seating area rotates around a center area featuring four stages. Each stage tells the story of a family at different time periods of the 20th century-the early 1900s, the 1920s the 1940s, and recent times-highlighting the technology advances in that time period The story of innovation is told from a hand-cranked washing machine, to electric lighting and radio, to automatic dishwashers and television, to computers and voice-activated appliances In every act, the father (who is also the narrator of the show)talks about the latest inventions and says "It cant get any better only to discover that in fact, it does get better in the next act as technology progresses Although Spring doesn't have quite as long a history as that displayed in the Car- ousel of Progress, I feel the same way about Spring as"Progress Dad felt about the 20th century. Each and every Spring application seems to make the lives of developers so much better. Just looking at how Spring components are declared and wired together, we can see the following progression over the history of Spring
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值