Extract code samples from docs

See gh-6313
pull/25617/head
Phillip Webb 4 years ago
parent c4432a81a8
commit bea307b115

@ -79,7 +79,9 @@ dependencies {
implementation("org.assertj:assertj-core")
implementation("org.glassfish.jersey.core:jersey-server")
implementation("org.hibernate:hibernate-jcache")
implementation("org.jooq:jooq")
implementation("org.slf4j:jul-to-slf4j")
implementation("org.springframework:spring-jdbc")
implementation("org.springframework:spring-test")
implementation("org.springframework:spring-web")
implementation("org.springframework:spring-webmvc")
@ -92,6 +94,7 @@ dependencies {
implementation("org.springframework.restdocs:spring-restdocs-restassured")
implementation("org.springframework.restdocs:spring-restdocs-webtestclient")
implementation("org.springframework.security:spring-security-config")
implementation("org.springframework.security:spring-security-oauth2-client")
implementation("org.springframework.security:spring-security-web")
implementation("org.junit.jupiter:junit-jupiter")
implementation("org.yaml:snakeyaml")

@ -2893,16 +2893,9 @@ Jersey has some native Spring support, so we also provide auto-configuration sup
To get started with Jersey, include the `spring-boot-starter-jersey` as a dependency and then you need one `@Bean` of type `ResourceConfig` in which you register all the endpoints, as shown in the following example:
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"]
[source,java,indent=0,subs="verbatim,quotes,attributes"]
----
@Component
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
register(Endpoint.class);
}
}
include::{include-springbootfeatures}/webapplications/jersey/JerseyConfig.java[]
----
WARNING: Jersey's support for scanning executable archives is rather limited.
@ -2913,18 +2906,9 @@ For more advanced customizations, you can also register an arbitrary number of b
All the registered endpoints should be `@Components` with HTTP resource annotations (`@GET` and others), as shown in the following example:
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"]
[source,java,indent=0,subs="verbatim,quotes,attributes"]
----
@Component
@Path("/hello")
public class Endpoint {
@GET
public String message() {
return "Hello";
}
}
include::{include-springbootfeatures}/webapplications/jersey/Endpoint.java[]
----
Since the `Endpoint` is a Spring `@Component`, its lifecycle is managed by Spring and you can use the `@Autowired` annotation to inject dependencies and use the `@Value` annotation to inject external configuration.
@ -3036,21 +3020,9 @@ If you need to programmatically configure your embedded servlet container, you c
`WebServerFactoryCustomizer` provides access to the `ConfigurableServletWebServerFactory`, which includes numerous customization setter methods.
The following example shows programmatically setting the port:
[source,java,pending-extract=true,indent=0]
[source,java,indent=0]
----
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;
@Component
public class CustomizationBean implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
@Override
public void customize(ConfigurableServletWebServerFactory server) {
server.setPort(9000);
}
}
include::{include-springbootfeatures}/webapplications/embeddedservletcontainer/CustomizationBean.java[]
----
`TomcatServletWebServerFactory`, `JettyServletWebServerFactory` and `UndertowServletWebServerFactory` are dedicated variants of `ConfigurableServletWebServerFactory` that have additional customization setter methods for Tomcat, Jetty and Undertow respectively.
@ -3058,7 +3030,7 @@ The following example shows how to customize `TomcatServletWebServerFactory` tha
[source,java,indent=0,subs="verbatim,quotes,attributes"]
----
include::{include-springbootfeatures}/webapplications/TomcatServerCustomizer.java[]
include::{include-springbootfeatures}/webapplications/embeddedservletcontainer/TomcatServerCustomizer.java[]
----
@ -3226,24 +3198,9 @@ This is done on purpose since this builder is stateful and you shouldn't create
The following code shows a typical example:
[source,java,pending-extract=true,indent=0]
[source,java,indent=0]
----
@Service
public class MyService {
private final Mono<RSocketRequester> rsocketRequester;
public MyService(RSocketRequester.Builder rsocketRequesterBuilder) {
this.rsocketRequester = rsocketRequesterBuilder
.connectTcp("example.org", 9898).cache();
}
public Mono<User> someRSocketCall(String name) {
return this.rsocketRequester.flatMap(req ->
req.route("user").data(name).retrieveMono(User.class));
}
}
include::{include-springbootfeatures}/rsocket/MyService.java[]
----
@ -3310,7 +3267,7 @@ Spring Boot provides convenience methods that can be used to override access rul
For example, you can customize your security configuration by adding something like:
[source,java,pending-extract=true,indent=0]
[source,java,indent=0]
----
include::{include-springbootfeatures}/security/CustomWebFluxSecurityConfiguration.java[]
----
@ -3389,19 +3346,9 @@ By default, Spring Security's `OAuth2LoginAuthenticationFilter` only processes U
If you want to customize the `redirect-uri` to use a different pattern, you need to provide configuration to process that custom pattern.
For example, for servlet applications, you can add your own `SecurityFilterChain` that resembles the following:
[source,java,pending-extract=true,indent=0]
[source,java,indent=0]
----
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2Login()
.redirectionEndpoint()
.baseUri("/custom-callback");
return http.build();
}
include::{include-springbootfeatures}/security/OAuthClientConfiguration.java[]
----
TIP: Spring Boot auto-configures an `InMemoryOAuth2AuthorizedClientService` which is used by Spring Security for the management of client registrations.
@ -3713,25 +3660,9 @@ For example, the following section in `application.properties` shows how you can
=== Using JdbcTemplate
Spring's `JdbcTemplate` and `NamedParameterJdbcTemplate` classes are auto-configured, and you can `@Autowire` them directly into your own beans, as shown in the following example:
[source,java,pending-extract=true,indent=0]
[source,java,indent=0]
----
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
private final JdbcTemplate jdbcTemplate;
@Autowired
public MyBean(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
// ...
}
include::{include-springbootfeatures}/sql/jdbctemplate/MyBean.java[]
----
You can customize some properties of the template by using the `spring.jdbc.template.*` properties, as shown in the following example:
@ -3773,49 +3704,9 @@ By default, all packages below your main configuration class (the one annotated
Any classes annotated with `@Entity`, `@Embeddable`, or `@MappedSuperclass` are considered.
A typical entity class resembles the following example:
[source,java,pending-extract=true,indent=0]
[source,java,indent=0]
----
package com.example.myapp.domain;
import java.io.Serializable;
import javax.persistence.*;
@Entity
public class City implements Serializable {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String state;
// ... additional members, often include @OneToMany mappings
protected City() {
// no-args constructor required by JPA spec
// this one is protected since it shouldn't be used directly
}
public City(String name, String state) {
this.name = name;
this.state = state;
}
public String getName() {
return this.name;
}
public String getState() {
return this.state;
}
// ... etc
}
include::{include-springbootfeatures}/sql/jpa/City.java[]
----
TIP: You can customize entity scanning locations by using the `@EntityScan` annotation.
@ -3836,20 +3727,9 @@ If you use auto-configuration, repositories are searched from the package contai
The following example shows a typical Spring Data repository interface definition:
[source,java,pending-extract=true,indent=0]
[source,java,indent=0]
----
package com.example.myapp.domain;
import org.springframework.data.domain.*;
import org.springframework.data.repository.*;
public interface CityRepository extends Repository<City, Long> {
Page<City> findAll(Pageable pageable);
City findByNameAndStateAllIgnoringCase(String name, String state);
}
include::{include-springbootfeatures}/sql/jpa/CityRepository.java[]
----
Spring Data JPA repositories support three different modes of bootstrapping: default, deferred, and lazy.
@ -3979,34 +3859,20 @@ The following listing shows an example:
==== Using DSLContext
The fluent API offered by jOOQ is initiated through the `org.jooq.DSLContext` interface.
Spring Boot auto-configures a `DSLContext` as a Spring Bean and connects it to your application `DataSource`.
To use the `DSLContext`, you can `@Autowire` it, as shown in the following example:
To use the `DSLContext`, you can inject it, as shown in the following example:
[source,java,pending-extract=true,indent=0]
[source,java,indent=0]
----
@Component
public class JooqExample implements CommandLineRunner {
private final DSLContext create;
@Autowired
public JooqExample(DSLContext dslContext) {
this.create = dslContext;
}
}
include::{include-springbootfeatures}/sql/jooq/JooqExample.java[tag=!method]
----
TIP: The jOOQ manual tends to use a variable named `create` to hold the `DSLContext`.
You can then use the `DSLContext` to construct your queries, as shown in the following example:
[source,java,pending-extract=true,indent=0]
[source,java,indent=0]
----
public List<GregorianCalendar> authorsBornAfter1980() {
return this.create.selectFrom(AUTHOR)
.where(AUTHOR.DATE_OF_BIRTH.greaterThan(new GregorianCalendar(1980, 0, 1)))
.fetch(AUTHOR.DATE_OF_BIRTH);
}
include::{include-springbootfeatures}/sql/jooq/JooqExample.java[tag=method]
----

@ -0,0 +1,43 @@
/*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.docs.springbootfeatures.rsocket;
import reactor.core.publisher.Mono;
import org.springframework.messaging.rsocket.RSocketRequester;
import org.springframework.stereotype.Service;
@Service
public class MyService {
private final RSocketRequester rsocketRequester;
public MyService(RSocketRequester.Builder rsocketRequesterBuilder) {
this.rsocketRequester = rsocketRequesterBuilder.tcp("example.org", 9898);
}
public Mono<User> someRSocketCall(String name) {
return this.rsocketRequester.route("user").data(name).retrieveMono(User.class);
}
}
// @chomp:file
class User {
}

@ -0,0 +1,34 @@
/*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.docs.springbootfeatures.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class OAuthClientConfiguration {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated();
http.oauth2Login().redirectionEndpoint().baseUri("custom-callback");
return http.build();
}
}

@ -0,0 +1,35 @@
/*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.docs.springbootfeatures.sql.jdbctemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
private final JdbcTemplate jdbcTemplate;
public MyBean(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void doSomething() {
/* @chomp:line this.jdbcTemplate ... */ this.jdbcTemplate.execute("delete from customer");
}
}

@ -0,0 +1,46 @@
/*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.docs.springbootfeatures.sql.jooq;
import java.util.GregorianCalendar;
import java.util.List;
import org.jooq.DSLContext;
import org.springframework.stereotype.Component;
import static org.springframework.boot.docs.springbootfeatures.sql.jooq.Tables.AUTHOR;
@Component
public class JooqExample {
private final DSLContext create;
public JooqExample(DSLContext dslContext) {
this.create = dslContext;
}
// tag::method[]
public List<GregorianCalendar> authorsBornAfter1980() {
// @formatter:off
return this.create.selectFrom(AUTHOR)
.where(AUTHOR.DATE_OF_BIRTH.greaterThan(new GregorianCalendar(1980, 0, 1)))
.fetch(AUTHOR.DATE_OF_BIRTH);
// @formatter:on
} // end::method[]
}

@ -0,0 +1,49 @@
/*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.docs.springbootfeatures.sql.jooq;
import java.util.GregorianCalendar;
import org.jooq.Name;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.impl.TableImpl;
import org.jooq.impl.TableRecordImpl;
abstract class Tables {
static final TAuthor AUTHOR = null;
abstract class TAuthor extends TableImpl<TAuthorRecord> {
TAuthor(Name name) {
super(name);
}
public final TableField<TAuthorRecord, GregorianCalendar> DATE_OF_BIRTH = null;
}
abstract class TAuthorRecord extends TableRecordImpl<TAuthorRecord> {
TAuthorRecord(Table<TAuthorRecord> table) {
super(table);
}
}
}

@ -0,0 +1,61 @@
/*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.docs.springbootfeatures.sql.jpa;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class City implements Serializable {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String state;
// ... additional members, often include @OneToMany mappings
protected City() {
// no-args constructor required by JPA spec
// this one is protected since it shouldn't be used directly
}
public City(String name, String state) {
this.name = name;
this.state = state;
}
public String getName() {
return this.name;
}
public String getState() {
return this.state;
}
// ... etc
}

@ -0,0 +1,29 @@
/*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.docs.springbootfeatures.sql.jpa;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.Repository;
public interface CityRepository extends Repository<City, Long> {
Page<City> findAll(Pageable pageable);
City findByNameAndStateAllIgnoringCase(String name, String state);
}

@ -0,0 +1,31 @@
/*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.docs.springbootfeatures.webapplications.embeddedservletcontainer;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;
@Component
public class CustomizationBean implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
@Override
public void customize(ConfigurableServletWebServerFactory server) {
server.setPort(9000);
}
}

@ -14,7 +14,7 @@
* limitations under the License.
*/
package org.springframework.boot.docs.springbootfeatures.webapplications;
package org.springframework.boot.docs.springbootfeatures.webapplications.embeddedservletcontainer;
import java.time.Duration;

@ -0,0 +1,33 @@
/*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.docs.springbootfeatures.webapplications.jersey;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import org.springframework.stereotype.Component;
@Component
@Path("/hello")
public class Endpoint {
@GET
public String message() {
return "Hello";
}
}

@ -0,0 +1,30 @@
/*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.docs.springbootfeatures.webapplications.jersey;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.stereotype.Component;
@Component
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
register(Endpoint.class);
}
}

@ -50,4 +50,5 @@
<suppress files="BsdDomainSocket" checks="FinalClass" message="SockaddrUn" />
<suppress files="StringSequence" checks="SpringMethodVisibility" message="isEmpty"/>
<suppress files="ValidatorPropertiesWithDefaultValues\.java" checks="SpringMethodVisibility" />
<suppress files="JooqExample.java" checks="SpringAvoidStaticImport" />
</suppressions>

Loading…
Cancel
Save