Commit 9aad29da authored by Phillip Webb's avatar Phillip Webb

Extract code samples from docs

See gh-6313
parent 0893df4a
plugins { plugins {
id "java" id "java"
id "groovy"
id "org.asciidoctor.jvm.convert" id "org.asciidoctor.jvm.convert"
id "org.asciidoctor.jvm.pdf" id "org.asciidoctor.jvm.pdf"
id "org.springframework.boot.conventions" id "org.springframework.boot.conventions"
...@@ -63,12 +64,17 @@ dependencies { ...@@ -63,12 +64,17 @@ dependencies {
gradlePluginDocumentation(project(path: ":spring-boot-project:spring-boot-tools:spring-boot-gradle-plugin", configuration: "documentation")) gradlePluginDocumentation(project(path: ":spring-boot-project:spring-boot-tools:spring-boot-gradle-plugin", configuration: "documentation"))
implementation(project(path: ":spring-boot-project:spring-boot-actuator")) implementation(project(path: ":spring-boot-project:spring-boot-actuator"))
implementation(project(path: ":spring-boot-project:spring-boot-actuator-autoconfigure"))
implementation(project(path: ":spring-boot-project:spring-boot-autoconfigure")) implementation(project(path: ":spring-boot-project:spring-boot-autoconfigure"))
implementation(project(path: ":spring-boot-project:spring-boot-cli"))
implementation(project(path: ":spring-boot-project:spring-boot-tools:spring-boot-loader-tools"))
implementation(project(path: ":spring-boot-project:spring-boot-test")) implementation(project(path: ":spring-boot-project:spring-boot-test"))
implementation(project(path: ":spring-boot-project:spring-boot-test-autoconfigure")) implementation(project(path: ":spring-boot-project:spring-boot-test-autoconfigure"))
implementation("ch.qos.logback:logback-classic") implementation("ch.qos.logback:logback-classic")
implementation("com.zaxxer:HikariCP") implementation("com.zaxxer:HikariCP")
implementation("io.micrometer:micrometer-core") implementation("io.micrometer:micrometer-core")
implementation("io.micrometer:micrometer-registry-graphite")
implementation("io.micrometer:micrometer-registry-jmx")
implementation("io.projectreactor.netty:reactor-netty-http") implementation("io.projectreactor.netty:reactor-netty-http")
implementation("io.r2dbc:r2dbc-postgresql") implementation("io.r2dbc:r2dbc-postgresql")
implementation("io.undertow:undertow-core") implementation("io.undertow:undertow-core")
...@@ -83,6 +89,7 @@ dependencies { ...@@ -83,6 +89,7 @@ dependencies {
implementation("org.apache.tomcat.embed:tomcat-embed-core") implementation("org.apache.tomcat.embed:tomcat-embed-core")
implementation("org.assertj:assertj-core") implementation("org.assertj:assertj-core")
implementation("org.glassfish.jersey.core:jersey-server") implementation("org.glassfish.jersey.core:jersey-server")
implementation("org.glassfish.jersey.containers:jersey-container-servlet-core")
implementation("org.hibernate:hibernate-jcache") implementation("org.hibernate:hibernate-jcache")
implementation("org.jooq:jooq") implementation("org.jooq:jooq")
implementation("org.mockito:mockito-core") implementation("org.mockito:mockito-core")
...@@ -94,14 +101,16 @@ dependencies { ...@@ -94,14 +101,16 @@ dependencies {
implementation("org.springframework:spring-orm") implementation("org.springframework:spring-orm")
implementation("org.springframework:spring-test") implementation("org.springframework:spring-test")
implementation("org.springframework:spring-web") implementation("org.springframework:spring-web")
implementation("org.springframework:spring-webmvc")
implementation("org.springframework:spring-webflux") implementation("org.springframework:spring-webflux")
implementation("org.springframework:spring-webmvc")
implementation("org.springframework:spring-websocket")
implementation("org.springframework.amqp:spring-amqp") implementation("org.springframework.amqp:spring-amqp")
implementation("org.springframework.amqp:spring-rabbit") implementation("org.springframework.amqp:spring-rabbit")
implementation("org.springframework.batch:spring-batch-core") implementation("org.springframework.batch:spring-batch-core")
implementation("org.springframework.data:spring-data-cassandra") implementation("org.springframework.data:spring-data-cassandra")
implementation("org.springframework.data:spring-data-couchbase") implementation("org.springframework.data:spring-data-couchbase")
implementation("org.springframework.data:spring-data-elasticsearch") implementation("org.springframework.data:spring-data-elasticsearch")
implementation("org.springframework.data:spring-data-jpa")
implementation("org.springframework.data:spring-data-ldap") implementation("org.springframework.data:spring-data-ldap")
implementation("org.springframework.data:spring-data-mongodb") implementation("org.springframework.data:spring-data-mongodb")
implementation("org.springframework.data:spring-data-neo4j") implementation("org.springframework.data:spring-data-neo4j")
...@@ -114,9 +123,12 @@ dependencies { ...@@ -114,9 +123,12 @@ dependencies {
implementation("org.springframework.restdocs:spring-restdocs-webtestclient") implementation("org.springframework.restdocs:spring-restdocs-webtestclient")
implementation("org.springframework.security:spring-security-config") implementation("org.springframework.security:spring-security-config")
implementation("org.springframework.security:spring-security-oauth2-client") implementation("org.springframework.security:spring-security-oauth2-client")
implementation("org.springframework.security:spring-security-test")
implementation("org.springframework.security:spring-security-web") implementation("org.springframework.security:spring-security-web")
implementation("org.springframework.ws:spring-ws-core") implementation("org.springframework.ws:spring-ws-core")
implementation("org.springframework.ws:spring-ws-test") implementation("org.springframework.ws:spring-ws-test")
implementation("org.testcontainers:junit-jupiter")
implementation("org.testcontainers:neo4j")
implementation("org.junit.jupiter:junit-jupiter") implementation("org.junit.jupiter:junit-jupiter")
implementation("org.yaml:snakeyaml") implementation("org.yaml:snakeyaml")
...@@ -273,6 +285,9 @@ syncDocumentationSourceForAsciidoctor { ...@@ -273,6 +285,9 @@ syncDocumentationSourceForAsciidoctor {
from("src/test/java") { from("src/test/java") {
into "test/java" into "test/java"
} }
from("src/main/groovy") {
into "main/groovy"
}
} }
syncDocumentationSourceForAsciidoctorMultipage { syncDocumentationSourceForAsciidoctorMultipage {
...@@ -291,6 +306,9 @@ syncDocumentationSourceForAsciidoctorMultipage { ...@@ -291,6 +306,9 @@ syncDocumentationSourceForAsciidoctorMultipage {
from("src/test/java") { from("src/test/java") {
into "test/java" into "test/java"
} }
from("src/main/groovy") {
into "main/groovy"
}
} }
syncDocumentationSourceForAsciidoctorPdf { syncDocumentationSourceForAsciidoctorPdf {
...@@ -309,6 +327,9 @@ syncDocumentationSourceForAsciidoctorPdf { ...@@ -309,6 +327,9 @@ syncDocumentationSourceForAsciidoctorPdf {
from("src/test/java") { from("src/test/java") {
into "test/java" into "test/java"
} }
from("src/main/groovy") {
into "main/groovy"
}
} }
task zip(type: Zip) { task zip(type: Zip) {
......
...@@ -320,15 +320,9 @@ If you wish to configure custom security for HTTP endpoints, for example, only a ...@@ -320,15 +320,9 @@ If you wish to configure custom security for HTTP endpoints, for example, only a
A typical Spring Security configuration might look something like the following example: A typical Spring Security configuration might look something like the following example:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
@Bean include::{docs-java}/actuator/endpoints/security/typical/MySecurityConfiguration.java[]
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests((requests) ->
requests.anyRequest().hasRole("ENDPOINT_ADMIN"));
http.httpBasic();
return http.build();
}
---- ----
The preceding example uses `EndpointRequest.toAnyEndpoint()` to match a request to any endpoint and then ensures that all have the `ENDPOINT_ADMIN` role. The preceding example uses `EndpointRequest.toAnyEndpoint()` to match a request to any endpoint and then ensures that all have the `ENDPOINT_ADMIN` role.
...@@ -349,14 +343,9 @@ You can do so by changing the configprop:management.endpoints.web.exposure.inclu ...@@ -349,14 +343,9 @@ You can do so by changing the configprop:management.endpoints.web.exposure.inclu
Additionally, if Spring Security is present, you would need to add custom security configuration that allows unauthenticated access to the endpoints as shown in the following example: Additionally, if Spring Security is present, you would need to add custom security configuration that allows unauthenticated access to the endpoints as shown in the following example:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
@Bean include::{docs-java}/actuator/endpoints/security/exposeall/MySecurityConfiguration.java[]
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests((requests) ->
requests.anyRequest().permitAll());
return http.build();
}
---- ----
NOTE: In both the examples above, the configuration applies only to the actuator endpoints. NOTE: In both the examples above, the configuration applies only to the actuator endpoints.
...@@ -751,25 +740,9 @@ You need to provide an implementation of the `health()` method and return a `Hea ...@@ -751,25 +740,9 @@ You need to provide an implementation of the `health()` method and return a `Hea
The `Health` response should include a status and can optionally include additional details to be displayed. The `Health` response should include a status and can optionally include additional details to be displayed.
The following code shows a sample `HealthIndicator` implementation: The following code shows a sample `HealthIndicator` implementation:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
import org.springframework.boot.actuate.health.Health; include::{docs-java}/actuator/endpoints/health/writingcustomhealthindicators/MyHealthIndicator.java[]
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class MyHealthIndicator implements HealthIndicator {
@Override
public Health health() {
int errorCode = check(); // perform some specific health check
if (errorCode != 0) {
return Health.down().withDetail("Error Code", errorCode).build();
}
return Health.up().build();
}
}
---- ----
NOTE: The identifier for a given `HealthIndicator` is the name of the bean without the `HealthIndicator` suffix, if it exists. NOTE: The identifier for a given `HealthIndicator` is the name of the bean without the `HealthIndicator` suffix, if it exists.
...@@ -845,18 +818,9 @@ If you need to register a regular `HealthContributor`, you should wrap it using ...@@ -845,18 +818,9 @@ If you need to register a regular `HealthContributor`, you should wrap it using
To provide custom health information from a reactive API, you can register Spring beans that implement the {spring-boot-actuator-module-code}/health/ReactiveHealthIndicator.java[`ReactiveHealthIndicator`] interface. To provide custom health information from a reactive API, you can register Spring beans that implement the {spring-boot-actuator-module-code}/health/ReactiveHealthIndicator.java[`ReactiveHealthIndicator`] interface.
The following code shows a sample `ReactiveHealthIndicator` implementation: The following code shows a sample `ReactiveHealthIndicator` implementation:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
@Component include::{docs-java}/actuator/endpoints/health/reactivehealthindicators/MyReactiveHealthIndicator.java[]
public class MyReactiveHealthIndicator implements ReactiveHealthIndicator {
@Override
public Mono<Health> health() {
return doHealthCheck() //perform some specific health check that returns a Mono<Health>
.onErrorResume(ex -> Mono.just(new Health.Builder().down(ex).build()));
}
}
---- ----
TIP: To handle the error automatically, consider extending from `AbstractReactiveHealthIndicator`. TIP: To handle the error automatically, consider extending from `AbstractReactiveHealthIndicator`.
...@@ -1218,24 +1182,9 @@ To provide custom application information, you can register Spring beans that im ...@@ -1218,24 +1182,9 @@ To provide custom application information, you can register Spring beans that im
The following example contributes an `example` entry with a single value: The following example contributes an `example` entry with a single value:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
import java.util.Collections; include::{docs-java}/actuator/endpoints/info/writingcustominfocontributors/MyInfoContributor.java[]
import org.springframework.boot.actuate.info.Info;
import org.springframework.boot.actuate.info.InfoContributor;
import org.springframework.stereotype.Component;
@Component
public class ExampleInfoContributor implements InfoContributor {
@Override
public void contribute(Info.Builder builder) {
builder.withDetail("example",
Collections.singletonMap("key", "value"));
}
}
---- ----
If you reach the `info` endpoint, you should see a response that contains the following additional entry: If you reach the `info` endpoint, you should see a response that contains the following additional entry:
......
...@@ -65,22 +65,16 @@ Spring Boot will also add any auto-configured registries to the global static co ...@@ -65,22 +65,16 @@ Spring Boot will also add any auto-configured registries to the global static co
You can register any number of `MeterRegistryCustomizer` beans to further configure the registry, such as applying common tags, before any meters are registered with the registry: You can register any number of `MeterRegistryCustomizer` beans to further configure the registry, such as applying common tags, before any meters are registered with the registry:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
@Bean include::{docs-java}/actuator/metrics/gettingstarted/commontags/MyMeterRegistryConfiguration.java
MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
return registry -> registry.config().commonTags("region", "us-east-1");
}
---- ----
You can apply customizations to particular registry implementations by being more specific about the generic type: You can apply customizations to particular registry implementations by being more specific about the generic type:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
@Bean include::{docs-java}/actuator/metrics/gettingstarted/specifictype/MyMeterRegistryConfiguration.java
MeterRegistryCustomizer<GraphiteMeterRegistry> graphiteMetricsNamingConvention() {
return registry -> registry.config().namingConvention(MY_CUSTOM_CONVENTION);
}
---- ----
Spring Boot also <<actuator#actuator.metrics.supported,configures built-in instrumentation>> that you can control via configuration or dedicated annotation markers. Spring Boot also <<actuator#actuator.metrics.supported,configures built-in instrumentation>> that you can control via configuration or dedicated annotation markers.
...@@ -233,12 +227,9 @@ Micrometer provides a default `HierarchicalNameMapper` that governs how a dimens ...@@ -233,12 +227,9 @@ Micrometer provides a default `HierarchicalNameMapper` that governs how a dimens
TIP: To take control over this behaviour, define your `GraphiteMeterRegistry` and supply your own `HierarchicalNameMapper`. TIP: To take control over this behaviour, define your `GraphiteMeterRegistry` and supply your own `HierarchicalNameMapper`.
An auto-configured `GraphiteConfig` and `Clock` beans are provided unless you define your own: An auto-configured `GraphiteConfig` and `Clock` beans are provided unless you define your own:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
@Bean include::{docs-java}/actuator/metrics/export/graphite/MyGraphiteConfiguration.java
public GraphiteMeterRegistry graphiteMeterRegistry(GraphiteConfig config, Clock clock) {
return new GraphiteMeterRegistry(config, clock, MY_HIERARCHICAL_MAPPER);
}
---- ----
...@@ -309,12 +300,9 @@ Micrometer provides a default `HierarchicalNameMapper` that governs how a dimens ...@@ -309,12 +300,9 @@ Micrometer provides a default `HierarchicalNameMapper` that governs how a dimens
TIP: To take control over this behaviour, define your `JmxMeterRegistry` and supply your own `HierarchicalNameMapper`. TIP: To take control over this behaviour, define your `JmxMeterRegistry` and supply your own `HierarchicalNameMapper`.
An auto-configured `JmxConfig` and `Clock` beans are provided unless you define your own: An auto-configured `JmxConfig` and `Clock` beans are provided unless you define your own:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
@Bean include::{docs-java}/actuator/metrics/export/jmx/MyJmxConfiguration.java
public JmxMeterRegistry jmxMeterRegistry(JmxConfig config, Clock clock) {
return new JmxMeterRegistry(config, clock, MY_HIERARCHICAL_MAPPER);
}
---- ----
...@@ -962,55 +950,23 @@ If supported, the annotation can be used either at the class-level or the method ...@@ -962,55 +950,23 @@ If supported, the annotation can be used either at the class-level or the method
For example, the following code shows how the annotation can be used to instrument all request mappings in a `@RestController`: For example, the following code shows how the annotation can be used to instrument all request mappings in a `@RestController`:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
@RestController include::{docs-java}/actuator/metrics/supported/timedannotation/all/MyController.java[]
@Timed
public class MyController {
@GetMapping("/api/addresses")
public List<Person> listAddress() { ... }
@GetMapping("/api/people")
public List<Person> listPeople() { ... }
}
---- ----
If you only want to instrument a single mapping, you can use the annotation on the method instead of the class: If you only want to instrument a single mapping, you can use the annotation on the method instead of the class:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
@RestController include::{docs-java}/actuator/metrics/supported/timedannotation/single/MyController.java[]
public class MyController {
@GetMapping("/api/addresses")
public List<Person> listAddress() { ... }
@GetMapping("/api/people")
@Timed
public List<Person> listPeople() { ... }
}
---- ----
You can also combine class-level and method-level annotations if you want to change timing details for a specific method: You can also combine class-level and method-level annotations if you want to change timing details for a specific method:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
@RestController include::{docs-java}/actuator/metrics/supported/timedannotation/change/MyController.java[]
@Timed
public class MyController {
@GetMapping("/api/addresses")
public List<Person> listPeople() { ... }
@GetMapping("/api/people")
@Timed(extraTags = { "region", "us-east-1" })
@Timed(value = "all.people", longTask = true)
public List<Person> listPeople() { ... }
}
---- ----
NOTE: A `@Timed` annotation with `longTask = true` will enable a long task timer for the method. NOTE: A `@Timed` annotation with `longTask = true` will enable a long task timer for the method.
......
...@@ -18,6 +18,7 @@ ...@@ -18,6 +18,7 @@
:github-issues: https://github.com/{github-repo}/issues/ :github-issues: https://github.com/{github-repo}/issues/
:github-wiki: https://github.com/{github-repo}/wiki :github-wiki: https://github.com/{github-repo}/wiki
:docs-java: ../../main/java/org/springframework/boot/docs :docs-java: ../../main/java/org/springframework/boot/docs
:docs-groovy: ../../main/groovy/org/springframework/boot/docs
:spring-boot-code: https://github.com/{github-repo}/tree/{github-tag} :spring-boot-code: https://github.com/{github-repo}/tree/{github-tag}
:spring-boot-api: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/api :spring-boot-api: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/api
:spring-boot-docs: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/reference :spring-boot-docs: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/reference
......
...@@ -37,15 +37,7 @@ An exception is thrown if more than one candidate is found. ...@@ -37,15 +37,7 @@ An exception is thrown if more than one candidate is found.
=== Example Repackage Implementation === Example Repackage Implementation
The following example shows a typical repackage implementation: The following example shows a typical repackage implementation:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
Repackager repackager = new Repackager(sourceJarFile); include::{docs-java}/buildtoolplugins/otherbuildsystems/examplerepackageimplementation/MyBuildTool.java[]
repackager.setBackupSource(false);
repackager.repackage(new Libraries() {
@Override
public void doWithLibraries(LibraryCallback callback) throws IOException {
// Build system specific implementation, callback for each dependency
// callback.library(new Library(nestedFile, LibraryScope.COMPILE));
}
});
---- ----
...@@ -59,15 +59,7 @@ The following example shows a "`hello world`" web application written in Groovy: ...@@ -59,15 +59,7 @@ The following example shows a "`hello world`" web application written in Groovy:
.hello.groovy .hello.groovy
[source,groovy,indent=0,subs="verbatim,quotes,attributes"] [source,groovy,indent=0,subs="verbatim,quotes,attributes"]
---- ----
@RestController include::{docs-groovy}/cli/usingthecli/run/WebApplication.groovy[tag=*]
class WebApplication {
@RequestMapping("/")
String home() {
"Hello World!"
}
}
---- ----
To compile and run the application, type the following command: To compile and run the application, type the following command:
...@@ -185,17 +177,16 @@ For example, consider the following declaration: ...@@ -185,17 +177,16 @@ For example, consider the following declaration:
[source,groovy,indent=0] [source,groovy,indent=0]
---- ----
@DependencyManagementBom("com.example.custom-bom:1.0.0") include::{docs-groovy}/cli/usingthecli/run/customdependencymanagement/single/CustomDependencyManagement.groovy[tag=*]
---- ----
The preceding declaration picks up `custom-bom-1.0.0.pom` in a Maven repository under `com/example/custom-versions/1.0.0/`. The preceding declaration picks up `custom-bom-1.0.0.pom` in a Maven repository under `com/example/custom-versions/1.0.0/`.
When you specify multiple BOMs, they are applied in the order in which you declare them, as shown in the following example: When you specify multiple BOMs, they are applied in the order in which you declare them, as shown in the following example:
[source,java,pending-extract=true,indent=0] [source,groovy,indent=0]
---- ----
@DependencyManagementBom(["com.example.custom-bom:1.0.0", include::{docs-groovy}/cli/usingthecli/run/customdependencymanagement/multiple/CustomDependencyManagement.groovy[tag=*]
"com.example.another-bom:1.0.0"])
---- ----
The preceding example indicates that the dependency management in `another-bom` overrides the dependency management in `custom-bom`. The preceding example indicates that the dependency management in `another-bom` overrides the dependency management in `custom-bom`.
......
...@@ -69,29 +69,9 @@ The annotation processor also supports the use of the `@Data`, `@Getter`, and `@ ...@@ -69,29 +69,9 @@ The annotation processor also supports the use of the `@Data`, `@Getter`, and `@
Consider the following example: Consider the following example:
[source,java,pending-extract=true,indent=0,subs="verbatim,attributes"] [source,java,indent=0,subs="verbatim,attributes"]
---- ----
@ConfigurationProperties(prefix="server") include::{docs-java}/configurationmetadata/annotationprocessor/automaticmetadatageneration/ServerProperties.java[]
public class ServerProperties {
/**
* Name of the server.
*/
private String name;
/**
* IP address to listen to.
*/
private String ip = "127.0.0.1";
/**
* Port to listener to.
*/
private int port = 9797;
// ... getter and setters
}
---- ----
This exposes three properties where `server.name` has no default and `server.ip` and `server.port` defaults to `"127.0.0.1"` and `9797` respectively. This exposes three properties where `server.name` has no default and `server.ip` and `server.port` defaults to `"127.0.0.1"` and `9797` respectively.
...@@ -106,25 +86,9 @@ Also, the annotation processor cannot auto-detect default values for ``Enum``s a ...@@ -106,25 +86,9 @@ Also, the annotation processor cannot auto-detect default values for ``Enum``s a
For cases where the default value could not be detected, <<configuration-metadata#configuration-metadata.annotation-processor.adding-additional-metadata,manual metadata>> should be provided. For cases where the default value could not be detected, <<configuration-metadata#configuration-metadata.annotation-processor.adding-additional-metadata,manual metadata>> should be provided.
Consider the following example: Consider the following example:
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"] [source,java,indent=0,subs="verbatim,quotes,attributes"]
---- ----
@ConfigurationProperties(prefix = "acme.messaging") include::{docs-java}/configurationmetadata/annotationprocessor/automaticmetadatageneration/MessagingProperties.java[]
public class MessagingProperties {
private List<String> addresses = new ArrayList<>(Arrays.asList("a", "b"));
private ContainerType containerType = ContainerType.SIMPLE;
// ... getter and setters
public enum ContainerType {
SIMPLE,
DIRECT
}
}
---- ----
In order to document default values for properties in the class above, you could add the following content to <<configuration-metadata#configuration-metadata.annotation-processor.adding-additional-metadata,the manual metadata of the module>>: In order to document default values for properties in the class above, you could add the following content to <<configuration-metadata#configuration-metadata.annotation-processor.adding-additional-metadata,the manual metadata of the module>>:
...@@ -153,28 +117,9 @@ The annotation processor automatically considers inner classes as nested propert ...@@ -153,28 +117,9 @@ The annotation processor automatically considers inner classes as nested propert
Rather than documenting the `ip` and `port` at the root of the namespace, we could create a sub-namespace for it. Rather than documenting the `ip` and `port` at the root of the namespace, we could create a sub-namespace for it.
Consider the updated example: Consider the updated example:
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"] [source,java,indent=0,subs="verbatim,quotes,attributes"]
---- ----
@ConfigurationProperties(prefix="server") include::{docs-java}/configurationmetadata/annotationprocessor/automaticmetadatageneration/nestedproperties/ServerProperties.java[]
public class ServerProperties {
private String name;
private Host host;
// ... getter and setters
public static class Host {
private String ip;
private int port;
// ... getter and setters
}
}
---- ----
The preceding example produces metadata information for `server.name`, `server.host.ip`, and `server.host.port` properties. The preceding example produces metadata information for `server.name`, `server.host.ip`, and `server.host.port` properties.
......
...@@ -207,28 +207,9 @@ Deprecation can also be specified declaratively in code by adding the `@Deprecat ...@@ -207,28 +207,9 @@ Deprecation can also be specified declaratively in code by adding the `@Deprecat
For instance, assume that the `app.acme.target` property was confusing and was renamed to `app.acme.name`. For instance, assume that the `app.acme.target` property was confusing and was renamed to `app.acme.name`.
The following example shows how to handle that situation: The following example shows how to handle that situation:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
@ConfigurationProperties("app.acme") include::{docs-java}/configurationmetadata/format/group/AcmeProperties.java[]
public class AcmeProperties {
private String name;
public String getName() { ... }
public void setName(String name) { ... }
@DeprecatedConfigurationProperty(replacement = "app.acme.name")
@Deprecated
public String getTarget() {
return getName();
}
@Deprecated
public void setTarget(String target) {
setName(target);
}
}
---- ----
NOTE: There is no way to set a `level`. NOTE: There is no way to set a `level`.
......
...@@ -18,14 +18,9 @@ The special `.keys` and `.values` suffixes must refer to the keys and the values ...@@ -18,14 +18,9 @@ The special `.keys` and `.values` suffixes must refer to the keys and the values
Assume a `sample.contexts` maps magic `String` values to an integer, as shown in the following example: Assume a `sample.contexts` maps magic `String` values to an integer, as shown in the following example:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
@ConfigurationProperties("sample") include::{docs-java}/configurationmetadata/manualhints/valuehint/SampleProperties.java[]
public class SampleProperties {
private Map<String,Integer> contexts;
// getters and setters
}
---- ----
The magic values are (in this example) are `sample1` and `sample2`. The magic values are (in this example) are `sample1` and `sample2`.
......
...@@ -93,21 +93,9 @@ Process-scoped environment variables are language agnostic. ...@@ -93,21 +93,9 @@ Process-scoped environment variables are language agnostic.
Environment variables do not always make for the easiest API, so Spring Boot automatically extracts them and flattens the data into properties that can be accessed through Spring's `Environment` abstraction, as shown in the following example: Environment variables do not always make for the easiest API, so Spring Boot automatically extracts them and flattens the data into properties that can be accessed through Spring's `Environment` abstraction, as shown in the following example:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
@Component include::{docs-java}/deployment/cloud/cloudfoundry/bindingtoservices/MyBean.java[]
class MyBean implements EnvironmentAware {
private String instanceId;
@Override
public void setEnvironment(Environment environment) {
this.instanceId = environment.getProperty("vcap.application.instance_id");
}
// ...
}
---- ----
All Cloud Foundry properties are prefixed with `vcap`. All Cloud Foundry properties are prefixed with `vcap`.
......
...@@ -149,26 +149,9 @@ If you run `mvn dependency:tree` again, you see that there are now a number of a ...@@ -149,26 +149,9 @@ If you run `mvn dependency:tree` again, you see that there are now a number of a
To finish our application, we need to create a single Java file. To finish our application, we need to create a single Java file.
By default, Maven compiles sources from `src/main/java`, so you need to create that directory structure and then add a file named `src/main/java/Example.java` to contain the following code: By default, Maven compiles sources from `src/main/java`, so you need to create that directory structure and then add a file named `src/main/java/Example.java` to contain the following code:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
import org.springframework.boot.*; include::{docs-java}/gettingstarted/firstapplication/code/Example.java[]
import org.springframework.boot.autoconfigure.*;
import org.springframework.web.bind.annotation.*;
@RestController
@EnableAutoConfiguration
public class Example {
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) {
SpringApplication.run(Example.class, args);
}
}
---- ----
Although there is not much code here, quite a lot is going on. Although there is not much code here, quite a lot is going on.
......
...@@ -13,13 +13,9 @@ If you need to externalize some settings, you can bind your `DataSource` to the ...@@ -13,13 +13,9 @@ If you need to externalize some settings, you can bind your `DataSource` to the
The following example shows how to define a data source in a bean: The following example shows how to define a data source in a bean:
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"] [source,java,indent=0,subs="verbatim,quotes,attributes"]
---- ----
@Bean include::{docs-java}/howto/dataaccess/configurecustomdatasource/FancyDataSourceConfiguration.java[]
@ConfigurationProperties(prefix="app.datasource")
public DataSource dataSource() {
return new FancyDataSource();
}
---- ----
The following example shows how to define a data source by setting properties: The following example shows how to define a data source by setting properties:
...@@ -190,16 +186,9 @@ For more about Spring Data, see the {spring-data}[Spring Data project page]. ...@@ -190,16 +186,9 @@ For more about Spring Data, see the {spring-data}[Spring Data project page].
Spring Boot tries to guess the location of your `@Entity` definitions, based on the `@EnableAutoConfiguration` it finds. Spring Boot tries to guess the location of your `@Entity` definitions, based on the `@EnableAutoConfiguration` it finds.
To get more control, you can use the `@EntityScan` annotation, as shown in the following example: To get more control, you can use the `@EntityScan` annotation, 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"]
---- ----
@Configuration(proxyBeanMethods = false) include::{docs-java}/howto/dataaccess/separateentitydefinitionsfromspringconfiguration/Application.java[]
@EnableAutoConfiguration
@EntityScan(basePackageClasses=City.class)
public class Application {
//...
}
---- ----
...@@ -255,7 +244,7 @@ This implementation provides the same table structure as Hibernate 4: all dots a ...@@ -255,7 +244,7 @@ This implementation provides the same table structure as Hibernate 4: all dots a
[source,java,indent=0] [source,java,indent=0]
---- ----
include::{docs-java}/howto/dataaccess/configurehibernatenamingstrategy/CaseSensitiveSpringPhysicalNamingStrategyConfiguration.java[] include::{docs-java}/howto/dataaccess/configurehibernatenamingstrategy/spring/MyHibernateConfiguration.java[]
---- ----
If you prefer to use Hibernate 5's default instead, set the following property: If you prefer to use Hibernate 5's default instead, set the following property:
...@@ -267,12 +256,9 @@ If you prefer to use Hibernate 5's default instead, set the following property: ...@@ -267,12 +256,9 @@ If you prefer to use Hibernate 5's default instead, set the following property:
Alternatively, you can configure the following bean: Alternatively, you can configure the following bean:
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"] [source,java,indent=0,subs="verbatim,quotes,attributes"]
---- ----
@Bean include::{docs-java}/howto/dataaccess/configurehibernatenamingstrategy/standard/MyHibernateConfiguration.java[]
public PhysicalNamingStrategy physicalNamingStrategy() {
return new PhysicalNamingStrategyStandardImpl();
}
---- ----
See {spring-boot-autoconfigure-module-code}/orm/jpa/HibernateJpaAutoConfiguration.java[`HibernateJpaAutoConfiguration`] and {spring-boot-autoconfigure-module-code}/orm/jpa/JpaBaseConfiguration.java[`JpaBaseConfiguration`] for more details. See {spring-boot-autoconfigure-module-code}/orm/jpa/HibernateJpaAutoConfiguration.java[`HibernateJpaAutoConfiguration`] and {spring-boot-autoconfigure-module-code}/orm/jpa/JpaBaseConfiguration.java[`JpaBaseConfiguration`] for more details.
...@@ -320,7 +306,7 @@ If you need to use JPA against multiple data sources, you likely need one `Entit ...@@ -320,7 +306,7 @@ If you need to use JPA against multiple data sources, you likely need one `Entit
The `LocalContainerEntityManagerFactoryBean` from Spring ORM allows you to configure an `EntityManagerFactory` for your needs. The `LocalContainerEntityManagerFactoryBean` from Spring ORM allows you to configure an `EntityManagerFactory` for your needs.
You can also reuse `JpaProperties` to bind settings for each `EntityManagerFactory`, as shown in the following example: You can also reuse `JpaProperties` to bind settings for each `EntityManagerFactory`, 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"]
---- ----
include::{docs-java}/howto/dataaccess/usemultipleentitymanagers/CustomEntityManagerFactoryConfiguration.java[] include::{docs-java}/howto/dataaccess/usemultipleentitymanagers/CustomEntityManagerFactoryConfiguration.java[]
---- ----
...@@ -337,23 +323,16 @@ You should provide a similar configuration for any additional data sources for w ...@@ -337,23 +323,16 @@ You should provide a similar configuration for any additional data sources for w
To complete the picture, you need to configure a `JpaTransactionManager` for each `EntityManagerFactory` as well. To complete the picture, you need to configure a `JpaTransactionManager` for each `EntityManagerFactory` as well.
Alternatively, you might be able to use a JTA transaction manager that spans both. Alternatively, you might be able to use a JTA transaction manager that spans both.
If you use Spring Data, you need to configure `@EnableJpaRepositories` accordingly, as shown in the following example: If you use Spring Data, you need to configure `@EnableJpaRepositories` accordingly, as shown in the following examples:
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"] [source,java,indent=0,subs="verbatim,quotes,attributes"]
----
include::{docs-java}/howto/dataaccess/usemultipleentitymanagers/OrderConfiguration.java[]
---- ----
@Configuration(proxyBeanMethods = false)
@EnableJpaRepositories(basePackageClasses = Order.class,
entityManagerFactoryRef = "firstEntityManagerFactory")
public class OrderConfiguration {
...
}
@Configuration(proxyBeanMethods = false) [source,java,indent=0,subs="verbatim,quotes,attributes"]
@EnableJpaRepositories(basePackageClasses = Customer.class, ----
entityManagerFactoryRef = "secondEntityManagerFactory") include::{docs-java}/howto/dataaccess/usemultipleentitymanagers/CustomerConfiguration.java[]
public class CustomerConfiguration {
...
}
---- ----
......
...@@ -24,15 +24,7 @@ To use Jersey alongside another web framework, such as Spring MVC, it should be ...@@ -24,15 +24,7 @@ To use Jersey alongside another web framework, such as Spring MVC, it should be
First, configure Jersey to use a Filter rather than a Servlet by configuring the configprop:spring.jersey.type[] application property with a value of `filter`. First, configure Jersey to use a Filter rather than a Servlet by configuring the configprop:spring.jersey.type[] application property with a value of `filter`.
Second, configure your `ResourceConfig` to forward requests that would have resulted in a 404, as shown in the following example. Second, configure your `ResourceConfig` to forward requests that would have resulted in a 404, 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 include::{docs-java}/howto/jersey/alongsideanotherwebframework/JerseyConfig.java[]
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
register(Endpoint.class);
property(ServletProperties.FILTER_FORWARD_ON_404, true);
}
}
---- ----
...@@ -11,19 +11,9 @@ If your JMS broker does not support transacted sessions, you have to disable the ...@@ -11,19 +11,9 @@ If your JMS broker does not support transacted sessions, you have to disable the
If you create your own `JmsListenerContainerFactory`, there is nothing to do, since, by default it cannot be transacted. If you create your own `JmsListenerContainerFactory`, there is nothing to do, since, by default it cannot be transacted.
If you want to use the `DefaultJmsListenerContainerFactoryConfigurer` to reuse Spring Boot's default, you can disable transacted sessions, as follows: If you want to use the `DefaultJmsListenerContainerFactoryConfigurer` to reuse Spring Boot's default, you can disable transacted sessions, as follows:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
@Bean include::{docs-java}/howto/messaging/disabletransactedjmssession/MyJmsConfiguration.java[]
public DefaultJmsListenerContainerFactory jmsListenerContainerFactory(
ConnectionFactory connectionFactory,
DefaultJmsListenerContainerFactoryConfigurer configurer) {
DefaultJmsListenerContainerFactory listenerFactory =
new DefaultJmsListenerContainerFactory();
configurer.configure(listenerFactory, connectionFactory);
listenerFactory.setTransactionManager(null);
listenerFactory.setSessionTransacted(false);
return listenerFactory;
}
---- ----
The preceding example overrides the default factory, and it should be applied to any other factory that your application defines, if any. The preceding example overrides the default factory, and it should be applied to any other factory that your application defines, if any.
...@@ -93,7 +93,7 @@ To use Spring property placeholders together with automatic expansion, escape th ...@@ -93,7 +93,7 @@ To use Spring property placeholders together with automatic expansion, escape th
[[howto.properties-and-configuration.externalize-configuration]] [[howto.properties-and-configuration.externalize-configuration]]
=== Externalize the Configuration of SpringApplication === Externalize the Configuration of SpringApplication
A `SpringApplication` has bean properties (mainly setters), so you can use its Java API as you create the application to modify its behavior. A `SpringApplication` has bean property setters, so you can use its Java API as you create the application to modify its behavior.
Alternatively, you can externalize the configuration by setting properties in `+spring.main.*+`. Alternatively, you can externalize the configuration by setting properties in `+spring.main.*+`.
For example, in `application.properties`, you might have the following settings: For example, in `application.properties`, you might have the following settings:
...@@ -107,28 +107,37 @@ For example, in `application.properties`, you might have the following settings: ...@@ -107,28 +107,37 @@ For example, in `application.properties`, you might have the following settings:
Then the Spring Boot banner is not printed on startup, and the application is not starting an embedded web server. Then the Spring Boot banner is not printed on startup, and the application is not starting an embedded web server.
Properties defined in external configuration override the values specified with the Java API, with the notable exception of the sources used to create the `ApplicationContext`. Properties defined in external configuration override and replace the values specified with the Java API, with the notable exception of the primary sources.
Consider the following application: Primary sources are those provided to the `SpringApplication` constructor:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
new SpringApplicationBuilder() include::{docs-java}/howto/propertiesandconfiguration/externalizeconfiguration/application/MyApplication.java[]
.bannerMode(Banner.Mode.OFF)
.sources(demo.MyApp.class)
.run(args);
---- ----
Now consider the following configuration: Or to `sources(...)` method of a `SpringApplicationBuilder`:
[source,java,indent=0]
----
include::{docs-java}/howto/propertiesandconfiguration/externalizeconfiguration/builder/MyApplication.java[]
----
Given the examples above, if we have the following configuration:
[source,yaml,indent=0,subs="verbatim,quotes,attributes",configprops,configblocks] [source,yaml,indent=0,subs="verbatim,quotes,attributes",configprops,configblocks]
---- ----
spring: spring:
main: main:
sources: "com.acme.Config,com.acme.ExtraConfig" sources: "com.example.MyDatabaseConfig,com.example.MyJmsConfig"
banner-mode: "console" banner-mode: "console"
---- ----
The actual application _now_ shows the banner (as overridden by configuration) and uses three sources for the `ApplicationContext` (in the following order): `demo.MyApp`, `com.acme.Config`, and `com.acme.ExtraConfig`. The actual application will show the banner (as overridden by configuration) and uses three sources for the `ApplicationContext`.
The application sources are:
.`MyApplication` (from the code)
.`MyDatabaseConfig` (from the external config)
.`MyJmsConfig`(from the external config)
......
...@@ -42,12 +42,7 @@ Alternatively, you can add the `RemoteIpValve` by customizing the `TomcatServlet ...@@ -42,12 +42,7 @@ Alternatively, you can add the `RemoteIpValve` by customizing the `TomcatServlet
To configure Spring Security to require a secure channel for all (or some) requests, consider adding your own `SecurityFilterChain` bean that adds the following `HttpSecurity` configuration: To configure Spring Security to require a secure channel for all (or some) requests, consider adding your own `SecurityFilterChain` bean that adds the following `HttpSecurity` configuration:
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"] [source,java,indent=0,subs="verbatim,quotes,attributes"]
---- ----
@Bean include::{docs-java}/howto/security/enablehttps/MySecurityConfig.java[]
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
// Customize the application security
http.requiresChannel().anyRequest().requiresSecure();
return http.build();
}
---- ----
...@@ -10,17 +10,9 @@ This section answers common questions about Spring MVC and Spring Boot. ...@@ -10,17 +10,9 @@ This section answers common questions about Spring MVC and Spring Boot.
=== Write a JSON REST Service === Write a JSON REST Service
Any Spring `@RestController` in a Spring Boot application should render JSON response by default as long as Jackson2 is on the classpath, as shown in the following example: Any Spring `@RestController` in a Spring Boot application should render JSON response by default as long as Jackson2 is on the classpath, 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"]
---- ----
@RestController include::{docs-java}/howto/springmvc/writejsonrestservice/MyController.java[]
public class MyController {
@RequestMapping("/thing")
public MyThing thing() {
return new MyThing();
}
}
---- ----
As long as `MyThing` can be serialized by Jackson2 (true for a normal POJO or Groovy object), then `http://localhost:8080/thing` serves a JSON representation of it by default. As long as `MyThing` can be serialized by Jackson2 (true for a normal POJO or Groovy object), then `http://localhost:8080/thing` serves a JSON representation of it by default.
...@@ -44,13 +36,9 @@ To use the Jackson XML renderer, add the following dependency to your project: ...@@ -44,13 +36,9 @@ To use the Jackson XML renderer, add the following dependency to your project:
If Jackson's XML extension is not available and JAXB is available, XML can be rendered with the additional requirement of having `MyThing` annotated as `@XmlRootElement`, as shown in the following example: If Jackson's XML extension is not available and JAXB is available, XML can be rendered with the additional requirement of having `MyThing` annotated as `@XmlRootElement`, 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"]
---- ----
@XmlRootElement include::{docs-java}/howto/springmvc/writexmlrestservice/MyThing.java[]
public class MyThing {
private String name;
// .. getters and setters
}
---- ----
JAXB is only available out of the box with Java 8. JAXB is only available out of the box with Java 8.
......
...@@ -5,16 +5,9 @@ It integrates with JUnit, allowing you to write a test class that can start up a ...@@ -5,16 +5,9 @@ It integrates with JUnit, allowing you to write a test class that can start up a
Testcontainers is especially useful for writing integration tests that talk to a real backend service such as MySQL, MongoDB, Cassandra etc. Testcontainers is especially useful for writing integration tests that talk to a real backend service such as MySQL, MongoDB, Cassandra etc.
Testcontainers can be used in a Spring Boot test as follows: Testcontainers can be used in a Spring Boot test as follows:
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"] [source,java,indent=0,subs="verbatim,quotes,attributes"]
---- ----
@SpringBootTest include::{docs-java}/howto/testcontainers/vanilla/MyIntegrationTests.java
@Testcontainers
class ExampleIntegrationTests {
@Container
static Neo4jContainer<?> neo4j = new Neo4jContainer<>();
}
---- ----
This will start up a docker container running Neo4j (if Docker is running locally) before any of the tests are run. This will start up a docker container running Neo4j (if Docker is running locally) before any of the tests are run.
...@@ -22,21 +15,9 @@ In most cases, you will need to configure the application using details from the ...@@ -22,21 +15,9 @@ In most cases, you will need to configure the application using details from the
This can be done with a static `@DynamicPropertySource` method that allows adding dynamic property values to the Spring Environment. This can be done with a static `@DynamicPropertySource` method that allows adding dynamic property values to the Spring Environment.
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"] [source,java,indent=0,subs="verbatim,quotes,attributes"]
---- ----
@SpringBootTest include::{docs-java}/howto/testcontainers/dynamicproperties/MyIntegrationTests.java
@Testcontainers
class ExampleIntegrationTests {
@Container
static Neo4jContainer<?> neo4j = new Neo4jContainer<>();
@DynamicPropertySource
static void neo4jProperties(DynamicPropertyRegistry registry) {
registry.add("spring.neo4j.uri", neo4j::getBoltUrl);
}
}
---- ----
The above configuration allows Neo4j-related beans in the application to communicate with Neo4j running inside the Testcontainers-managed Docker container. The above configuration allows Neo4j-related beans in the application to communicate with Neo4j running inside the Testcontainers-managed Docker container.
...@@ -3,15 +3,9 @@ ...@@ -3,15 +3,9 @@
Spring Security provides support for running tests as a specific user. Spring Security provides support for running tests as a specific user.
For example, the test in the snippet below will run with an authenticated user that has the `ADMIN` role. For example, the test in the snippet below will run with an authenticated user that has the `ADMIN` role.
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
@Test include::{docs-java}/howto/testingwithspringsecurity/MySecurityTests.java[]
@WithMockUser(roles="ADMIN")
public void requestProtectedUrlWithUser() throws Exception {
mvc
.perform(get("/"))
...
}
---- ----
Spring Security provides comprehensive integration with Spring MVC Test and this can also be used when testing controllers using the `@WebMvcTest` slice and `MockMvc`. Spring Security provides comprehensive integration with Spring MVC Test and this can also be used when testing controllers using the `@WebMvcTest` slice and `MockMvc`.
......
...@@ -14,21 +14,9 @@ The first step in producing a deployable war file is to provide a `SpringBootSer ...@@ -14,21 +14,9 @@ The first step in producing a deployable war file is to provide a `SpringBootSer
Doing so makes use of Spring Framework's Servlet 3.0 support and lets you configure your application when it is launched by the servlet container. Doing so makes use of Spring Framework's Servlet 3.0 support and lets you configure your application when it is launched by the servlet container.
Typically, you should update your application's main class to extend `SpringBootServletInitializer`, as shown in the following example: Typically, you should update your application's main class to extend `SpringBootServletInitializer`, 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"]
---- ----
@SpringBootApplication include::{docs-java}/howto/traditionaldeployment/war/MyApplication.java[]
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
---- ----
The next step is to update your build configuration such that your project produces a war file rather than a jar file. The next step is to update your build configuration such that your project produces a war file rather than a jar file.
...@@ -91,20 +79,9 @@ See the https://spring.io/guides/gs/convert-jar-to-war/[Getting Started Guide on ...@@ -91,20 +79,9 @@ See the https://spring.io/guides/gs/convert-jar-to-war/[Getting Started Guide on
To create a deployable war by extending `SpringBootServletInitializer` (for example, in a class called `Application`) and adding the Spring Boot `@SpringBootApplication` annotation, use code similar to that shown in the following example: To create a deployable war by extending `SpringBootServletInitializer` (for example, in a class called `Application`) and adding the Spring Boot `@SpringBootApplication` annotation, use code similar to that shown in the following example:
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"] [source,java,indent=0,subs="verbatim,quotes,attributes"]
---- ----
@SpringBootApplication include::{docs-java}/howto/traditionaldeployment/convertexistingapplication/MyApplication.java[tag=!main]
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
// Customize the application or call application.sources(...) to add sources
// Since our example is itself a @Configuration class (via @SpringBootApplication)
// we actually don't need to override this method.
return application;
}
}
---- ----
Remember that, whatever you put in the `sources` is merely a Spring `ApplicationContext`. Remember that, whatever you put in the `sources` is merely a Spring `ApplicationContext`.
...@@ -124,36 +101,18 @@ If you have other features in your application (for instance, using other servle ...@@ -124,36 +101,18 @@ If you have other features in your application (for instance, using other servle
Once the war file is working, you can make it executable by adding a `main` method to your `Application`, as shown in the following example: Once the war file is working, you can make it executable by adding a `main` method to your `Application`, 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"]
---- ----
public static void main(String[] args) { include::{docs-java}/howto/traditionaldeployment/convertexistingapplication/MyApplication.java[tag=main]
SpringApplication.run(Application.class, args);
}
---- ----
[NOTE] [NOTE]
==== ====
If you intend to start your application as a war or as an executable application, you need to share the customizations of the builder in a method that is both available to the `SpringBootServletInitializer` callback and in the `main` method in a class similar to the following: If you intend to start your application as a war or as an executable application, you need to share the customizations of the builder in a method that is both available to the `SpringBootServletInitializer` callback and in the `main` method in a class similar to the following:
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"] [source,java,indent=0,subs="verbatim,quotes,attributes"]
---- ----
@SpringBootApplication include::{docs-java}/howto/traditionaldeployment/convertexistingapplication/both/MyApplication.java[]
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return configureApplication(builder);
}
public static void main(String[] args) {
configureApplication(new SpringApplicationBuilder()).run(args);
}
private static SpringApplicationBuilder configureApplication(SpringApplicationBuilder builder) {
return builder.sources(Application.class).bannerMode(Banner.Mode.OFF);
}
}
---- ----
==== ====
...@@ -185,16 +144,9 @@ To deploy a Spring Boot application to WebLogic, you must ensure that your servl ...@@ -185,16 +144,9 @@ To deploy a Spring Boot application to WebLogic, you must ensure that your servl
A typical initializer for WebLogic should resemble the following example: A typical initializer for WebLogic should resemble the following example:
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"] [source,java,indent=0,subs="verbatim,quotes,attributes"]
---- ----
import org.springframework.boot.autoconfigure.SpringBootApplication; include::{docs-java}/howto/traditionaldeployment/weblogic/MyApplication.java[]
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.web.WebApplicationInitializer;
@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer implements WebApplicationInitializer {
}
---- ----
If you use Logback, you also need to tell WebLogic to prefer the packaged version rather than the version that was pre-installed with the server. If you use Logback, you also need to tell WebLogic to prefer the packaged version rather than the version that was pre-installed with the server.
......
...@@ -104,17 +104,9 @@ The best way to get that and be sure it has been initialized is to add a `@Bean` ...@@ -104,17 +104,9 @@ The best way to get that and be sure it has been initialized is to add a `@Bean`
Tests that use `@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)` can also inject the actual port into a field by using the `@LocalServerPort` annotation, as shown in the following example: Tests that use `@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)` can also inject the actual port into a field by using the `@LocalServerPort` annotation, 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"]
---- ----
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT) include::{docs-java}/howto/webserver/discoverport/MyWebIntegrationTests.java[]
public class MyWebIntegrationTests {
@LocalServerPort
int port;
// ...
}
---- ----
[NOTE] [NOTE]
...@@ -254,17 +246,9 @@ You can declare such a component and get access to the server factory relevant t ...@@ -254,17 +246,9 @@ You can declare such a component and get access to the server factory relevant t
The example below is for Tomcat with the `spring-boot-starter-web` (Servlet stack): The example below is for Tomcat with the `spring-boot-starter-web` (Servlet stack):
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"] [source,java,indent=0,subs="verbatim,quotes,attributes"]
---- ----
@Component include::{docs-java}/howto/webserver/configure/MyTomcatWebServerCustomizer.java[]
public class MyTomcatWebServerCustomizer
implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
@Override
public void customize(TomcatServletWebServerFactory factory) {
// customize the factory here
}
}
---- ----
NOTE: Spring Boot uses that infrastructure internally to auto-configure the server. NOTE: Spring Boot uses that infrastructure internally to auto-configure the server.
...@@ -335,14 +319,9 @@ Like any other Spring bean, you can define the order of Servlet filter beans; pl ...@@ -335,14 +319,9 @@ Like any other Spring bean, you can define the order of Servlet filter beans; pl
As <<howto#howto.webserver.add-servlet-filter-listener.spring-bean,described earlier>>, any `Servlet` or `Filter` beans are registered with the servlet container automatically. As <<howto#howto.webserver.add-servlet-filter-listener.spring-bean,described earlier>>, any `Servlet` or `Filter` beans are registered with the servlet container automatically.
To disable registration of a particular `Filter` or `Servlet` bean, create a registration bean for it and mark it as disabled, as shown in the following example: To disable registration of a particular `Filter` or `Servlet` bean, create a registration bean for it and mark it as disabled, 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"]
---- ----
@Bean include::{docs-java}/howto/webserver/addservletfilterlistener/springbean/disable/MyFilterConfiguration.java[]
public FilterRegistrationBean registration(MyFilter filter) {
FilterRegistrationBean registration = new FilterRegistrationBean(filter);
registration.setEnabled(false);
return registration;
}
---- ----
...@@ -520,12 +499,9 @@ include::{docs-java}/howto/webserver/enablemultiplelistenersinundertow/UndertowM ...@@ -520,12 +499,9 @@ include::{docs-java}/howto/webserver/enablemultiplelistenersinundertow/UndertowM
=== Create WebSocket Endpoints Using @ServerEndpoint === Create WebSocket Endpoints Using @ServerEndpoint
If you want to use `@ServerEndpoint` in a Spring Boot application that used an embedded container, you must declare a single `ServerEndpointExporter` `@Bean`, as shown in the following example: If you want to use `@ServerEndpoint` in a Spring Boot application that used an embedded container, you must declare a single `ServerEndpointExporter` `@Bean`, 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"]
---- ----
@Bean include::{docs-java}/howto/webserver/createwebsocketendpointsusingserverendpoint/MyWebSocketConfiguration.java[]
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
---- ----
The bean shown in the preceding example registers any `@ServerEndpoint` annotated beans with the underlying WebSocket container. The bean shown in the preceding example registers any `@ServerEndpoint` annotated beans with the underlying WebSocket container.
......
...@@ -25,14 +25,9 @@ Doing so enables debug logs for a selection of core loggers and logs a condition ...@@ -25,14 +25,9 @@ Doing so enables debug logs for a selection of core loggers and logs a condition
=== Disabling Specific Auto-configuration Classes === Disabling Specific Auto-configuration Classes
If you find that specific auto-configuration classes that you do not want are being applied, you can use the exclude attribute of `@SpringBootApplication` to disable them, as shown in the following example: If you find that specific auto-configuration classes that you do not want are being applied, you can use the exclude attribute of `@SpringBootApplication` to disable them, as shown in the following example:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
import org.springframework.boot.autoconfigure.*; include::{docs-java}/using/autoconfiguration/disablingspecific/MyApplication.java[]
import org.springframework.boot.autoconfigure.jdbc.*;
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
public class MyApplication {
}
---- ----
If the class is not on the classpath, you can use the `excludeName` attribute of the annotation and specify the fully qualified name instead. If the class is not on the classpath, you can use the `excludeName` attribute of the annotation and specify the fully qualified name instead.
......
...@@ -162,12 +162,9 @@ In most cases, you can set this property in your `application.properties` (doing ...@@ -162,12 +162,9 @@ In most cases, you can set this property in your `application.properties` (doing
If you need to _completely_ disable restart support (for example, because it does not work with a specific library), you need to set the configprop:spring.devtools.restart.enabled[] `System` property to `false` before calling `SpringApplication.run(...)`, as shown in the following example: If you need to _completely_ disable restart support (for example, because it does not work with a specific library), you need to set the configprop:spring.devtools.restart.enabled[] `System` property to `false` before calling `SpringApplication.run(...)`, as shown in the following example:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
public static void main(String[] args) { include::{docs-java}/devtools/restart/disable/MyApplication.java[]
System.setProperty("spring.devtools.restart.enabled", "false");
SpringApplication.run(MyApp.class, args);
}
---- ----
......
[[using.spring-beans-and-dependency-injection]] [[using.spring-beans-and-dependency-injection]]
== Spring Beans and Dependency Injection == Spring Beans and Dependency Injection
You are free to use any of the standard Spring Framework techniques to define your beans and their injected dependencies. You are free to use any of the standard Spring Framework techniques to define your beans and their injected dependencies.
We often find that using `@ComponentScan` (to find your beans) and using `@Autowired` (to do constructor injection) works well. We generally recommend using constructor injection to wire up dependencies and `@ComponentScan` to find beans.
If you structure your code as suggested above (locating your application class in a root package), you can add `@ComponentScan` without any arguments. If you structure your code as suggested above (locating your application class in a top package), you can add `@ComponentScan` without any arguments or use the `@SpringBootApplication` annotation which implicitly includes it.
All of your application components (`@Component`, `@Service`, `@Repository`, `@Controller` etc.) are automatically registered as Spring Beans. All of your application components (`@Component`, `@Service`, `@Repository`, `@Controller` etc.) are automatically registered as Spring Beans.
The following example shows a `@Service` Bean that uses constructor injection to obtain a required `RiskAssessor` bean: The following example shows a `@Service` Bean that uses constructor injection to obtain a required `RiskAssessor` bean:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
package com.example.service; include::{docs-java}/using/springbeansanddependencyinjection/singleconstructor/DatabaseAccountService.java[]
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class DatabaseAccountService implements AccountService {
private final RiskAssessor riskAssessor;
@Autowired
public DatabaseAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}
// ...
}
---- ----
If a bean has one constructor, you can omit the `@Autowired`, as shown in the following example: If a bean has more than one constructor, you'll need to mark the one you want Spring to use with `@Autowired`:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
@Service include::{docs-java}/using/springbeansanddependencyinjection/multipleconstructors/DatabaseAccountService.java[]
public class DatabaseAccountService implements AccountService {
private final RiskAssessor riskAssessor;
public DatabaseAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}
// ...
}
---- ----
TIP: Notice how using constructor injection lets the `riskAssessor` field be marked as `final`, indicating that it cannot be subsequently changed. TIP: Notice how using constructor injection lets the `riskAssessor` field be marked as `final`, indicating that it cannot be subsequently changed.
...@@ -31,7 +31,7 @@ The following listing shows a typical layout: ...@@ -31,7 +31,7 @@ The following listing shows a typical layout:
com com
+- example +- example
+- myapplication +- myapplication
+- Application.java +- MyApplication.java
| |
+- customer +- customer
| +- Customer.java | +- Customer.java
...@@ -46,21 +46,9 @@ The following listing shows a typical layout: ...@@ -46,21 +46,9 @@ The following listing shows a typical layout:
+- OrderRepository.java +- OrderRepository.java
---- ----
The `Application.java` file would declare the `main` method, along with the basic `@SpringBootApplication`, as follows: The `MyApplication.java` file would declare the `main` method, along with the basic `@SpringBootApplication`, as follows:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
package com.example.myapplication; include::{docs-java}/using/structuringyourcode/locatingthemainclass/MyApplication.java[]
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
---- ----
...@@ -7,21 +7,9 @@ A single `@SpringBootApplication` annotation can be used to enable those three f ...@@ -7,21 +7,9 @@ A single `@SpringBootApplication` annotation can be used to enable those three f
* `@ComponentScan`: enable `@Component` scan on the package where the application is located (see <<using#using.structuring-your-code,the best practices>>) * `@ComponentScan`: enable `@Component` scan on the package where the application is located (see <<using#using.structuring-your-code,the best practices>>)
* `@Configuration`: allow to register extra beans in the context or import additional configuration classes * `@Configuration`: allow to register extra beans in the context or import additional configuration classes
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
package com.example.myapplication; include::{docs-java}/using/usingthespringbootapplicationannotation/springapplication/MyApplication.java[]
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
---- ----
NOTE: `@SpringBootApplication` also provides aliases to customize the attributes of `@EnableAutoConfiguration` and `@ComponentScan`. NOTE: `@SpringBootApplication` also provides aliases to customize the attributes of `@EnableAutoConfiguration` and `@ComponentScan`.
...@@ -31,25 +19,9 @@ NOTE: `@SpringBootApplication` also provides aliases to customize the attributes ...@@ -31,25 +19,9 @@ NOTE: `@SpringBootApplication` also provides aliases to customize the attributes
None of these features are mandatory and you may choose to replace this single annotation by any of the features that it enables. None of these features are mandatory and you may choose to replace this single annotation by any of the features that it enables.
For instance, you may not want to use component scan or configuration properties scan in your application: For instance, you may not want to use component scan or configuration properties scan in your application:
[source,java,pending-extract=true,indent=0] [source,java,indent=0]
---- ----
package com.example.myapplication; include::{docs-java}/using/usingthespringbootapplicationannotation/individualannotations/MyApplication.java[]
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@Import({ MyConfig.class, MyAnotherConfig.class })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
---- ----
In this example, `Application` is just like any other Spring Boot application except that `@Component`-annotated classes and `@ConfigurationProperties`-annotated classes are not detected automatically and the user-defined beans are imported explicitly (see `@Import`). In this example, `Application` is just like any other Spring Boot application except that `@Component`-annotated classes and `@ConfigurationProperties`-annotated classes are not detected automatically and the user-defined beans are imported explicitly (see `@Import`).
......
/*
* 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.cli.usingthecli.run;
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.bind.annotation.RequestMapping
// tag::code[]
@RestController
class WebApplication {
@RequestMapping("/")
String home() {
"Hello World!"
}
}
// end::code[]
/*
* 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.cli.usingthecli.run.customdependencymanagement.multiple;
import org.springframework.boot.groovy.DependencyManagementBom;
// tag::code[]
@DependencyManagementBom([
"com.example.custom-bom:1.0.0",
"com.example.another-bom:1.0.0"])
// end::code[]
class CustomDependencyManagement {
}
/*
* 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.cli.usingthecli.run.customdependencymanagement.single;
import org.springframework.boot.groovy.DependencyManagementBom;
// tag::code[]
@DependencyManagementBom("com.example.custom-bom:1.0.0")
// end::code[]
class CustomDependencyManagement {
}
/*
* 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.actuator.endpoints.health.reactivehealthindicators;
import reactor.core.publisher.Mono;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.ReactiveHealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class MyReactiveHealthIndicator implements ReactiveHealthIndicator {
@Override
public Mono<Health> health() {
return doHealthCheck().onErrorResume((exception) -> Mono.just(new Health.Builder().down(exception).build()));
}
private Mono<Health> doHealthCheck() {
// perform some specific health check
return /**/ null;
}
}
/*
* 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.actuator.endpoints.health.writingcustomhealthindicators;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class MyHealthIndicator implements HealthIndicator {
@Override
public Health health() {
int errorCode = check();
if (errorCode != 0) {
return Health.down().withDetail("Error Code", errorCode).build();
}
return Health.up().build();
}
private int check() {
// perform some specific health check
return /**/ 0;
}
}
/*
* 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.actuator.endpoints.info.writingcustominfocontributors;
import java.util.Collections;
import org.springframework.boot.actuate.info.Info;
import org.springframework.boot.actuate.info.InfoContributor;
import org.springframework.stereotype.Component;
@Component
public class MyInfoContributor implements InfoContributor {
@Override
public void contribute(Info.Builder builder) {
builder.withDetail("example", Collections.singletonMap("key", "value"));
}
}
/*
* 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.actuator.endpoints.security.exposeall;
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
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(proxyBeanMethods = false)
public class MySecurityConfiguration {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.toAnyEndpoint())
.authorizeRequests((requests) -> requests.anyRequest().permitAll());
return http.build();
}
}
/*
* 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.actuator.endpoints.security.typical;
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
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(proxyBeanMethods = false)
public class MySecurityConfiguration {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.toAnyEndpoint())
.authorizeRequests((requests) -> requests.anyRequest().hasRole("ENDPOINT_ADMIN"));
http.httpBasic();
return http.build();
}
}
/*
* 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.actuator.metrics.export.graphite;
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.config.NamingConvention;
import io.micrometer.core.instrument.util.HierarchicalNameMapper;
import io.micrometer.graphite.GraphiteConfig;
import io.micrometer.graphite.GraphiteMeterRegistry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
public class MyGraphiteConfiguration {
@Bean
public GraphiteMeterRegistry graphiteMeterRegistry(GraphiteConfig config, Clock clock) {
return new GraphiteMeterRegistry(config, clock, this::toHierarchicalName);
}
private String toHierarchicalName(Meter.Id id, NamingConvention convention) {
return /**/ HierarchicalNameMapper.DEFAULT.toHierarchicalName(id, convention);
}
}
/*
* 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.actuator.metrics.export.jmx;
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.config.NamingConvention;
import io.micrometer.core.instrument.util.HierarchicalNameMapper;
import io.micrometer.jmx.JmxConfig;
import io.micrometer.jmx.JmxMeterRegistry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
public class MyJmxConfiguration {
@Bean
public JmxMeterRegistry jmxMeterRegistry(JmxConfig config, Clock clock) {
return new JmxMeterRegistry(config, clock, this::toHierarchicalName);
}
private String toHierarchicalName(Meter.Id id, NamingConvention convention) {
return /**/ HierarchicalNameMapper.DEFAULT.toHierarchicalName(id, convention);
}
}
/*
* 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.actuator.metrics.gettingstarted.commontags;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
public class MyMeterRegistryConfiguration {
@Bean
public MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
return (registry) -> registry.config().commonTags("region", "us-east-1");
}
}
/*
* 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.actuator.metrics.gettingstarted.specifictype;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.config.NamingConvention;
import io.micrometer.graphite.GraphiteMeterRegistry;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
public class MyMeterRegistryConfiguration {
@Bean
MeterRegistryCustomizer<GraphiteMeterRegistry> graphiteMetricsNamingConvention() {
return (registry) -> registry.config().namingConvention(this::name);
}
private String name(String name, Meter.Type type, String baseUnit) {
return /**/ NamingConvention.snakeCase.name(name, type, baseUnit);
}
}
/*
* 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.actuator.metrics.supported.timedannotation.all;
class Address {
}
/*
* 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.actuator.metrics.supported.timedannotation.all;
import java.util.List;
import io.micrometer.core.annotation.Timed;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Timed
public class MyController {
@GetMapping("/api/addresses")
public List<Address> listAddress() {
return /**/ null;
}
@GetMapping("/api/people")
public List<Person> listPeople() {
return /**/ null;
}
}
/*
* 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.actuator.metrics.supported.timedannotation.all;
class Person {
}
/*
* 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.actuator.metrics.supported.timedannotation.change;
class Address {
}
/*
* 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.actuator.metrics.supported.timedannotation.change;
import java.util.List;
import io.micrometer.core.annotation.Timed;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Timed
public class MyController {
@GetMapping("/api/addresses")
public List<Address> listAddress() {
return /**/ null;
}
@GetMapping("/api/people")
@Timed(extraTags = { "region", "us-east-1" })
@Timed(value = "all.people", longTask = true)
public List<Person> listPeople() {
return /**/ null;
}
}
/*
* 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.actuator.metrics.supported.timedannotation.change;
class Person {
}
/*
* 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.actuator.metrics.supported.timedannotation.single;
class Address {
}
/*
* 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.actuator.metrics.supported.timedannotation.single;
import java.util.List;
import io.micrometer.core.annotation.Timed;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/api/addresses")
public List<Address> listAddress() {
return /**/ null;
}
@GetMapping("/api/people")
@Timed
public List<Person> listPeople() {
return /**/ null;
}
}
/*
* 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.actuator.metrics.supported.timedannotation.single;
class Person {
}
/*
* 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.buildtoolplugins.otherbuildsystems.examplerepackageimplementation;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.springframework.boot.loader.tools.Library;
import org.springframework.boot.loader.tools.LibraryCallback;
import org.springframework.boot.loader.tools.LibraryScope;
import org.springframework.boot.loader.tools.Repackager;
public class MyBuildTool {
public void build() throws IOException {
File sourceJarFile = /**/ null;
Repackager repackager = new Repackager(sourceJarFile);
repackager.setBackupSource(false);
repackager.repackage(this::getLibraries);
}
private void getLibraries(LibraryCallback callback) throws IOException {
// Build system specific implementation, callback for each dependency
for (File nestedJar : getCompileScopeJars()) {
callback.library(new Library(nestedJar, LibraryScope.COMPILE));
}
// ...
}
private List<File> getCompileScopeJars() {
return /**/ null;
}
}
/*
* 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.configurationmetadata.annotationprocessor.automaticmetadatageneration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "acme.messaging")
public class MessagingProperties {
private List<String> addresses = new ArrayList<>(Arrays.asList("a", "b"));
private ContainerType containerType = ContainerType.SIMPLE;
// @fold:on // getters/setters ...
public List<String> getAddresses() {
return this.addresses;
}
public void setAddresses(List<String> addresses) {
this.addresses = addresses;
}
public ContainerType getContainerType() {
return this.containerType;
}
public void setContainerType(ContainerType containerType) {
this.containerType = containerType;
}
// @fold:off
public enum ContainerType {
SIMPLE, DIRECT
}
}
/*
* 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.configurationmetadata.annotationprocessor.automaticmetadatageneration;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "server")
public class ServerProperties {
/**
* Name of the server.
*/
private String name;
/**
* IP address to listen to.
*/
private String ip = "127.0.0.1";
/**
* Port to listener to.
*/
private int port = 9797;
// @fold:on // getters/setters ...
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getIp() {
return this.ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
// fold:off
}
/*
* 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.configurationmetadata.annotationprocessor.automaticmetadatageneration.nestedproperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "server")
public class ServerProperties {
private String name;
private Host host;
// @fold:on // getters/setters ...
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Host getHost() {
return this.host;
}
public void setHost(Host host) {
this.host = host;
}
// @fold:off
public static class Host {
private String ip;
private int port;
// @fold:on // getters/setters ...
public String getIp() {
return this.ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
// @fold:off // getters/setters ...
}
}
/*
* 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.configurationmetadata.format.group;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.DeprecatedConfigurationProperty;
@ConfigurationProperties("app.acme")
public class AcmeProperties {
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Deprecated
@DeprecatedConfigurationProperty(replacement = "app.acme.name")
public String getTarget() {
return this.name;
}
@Deprecated
public void setTarget(String target) {
this.name = target;
}
}
/*
* 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.configurationmetadata.manualhints.valuehint;
import java.util.Map;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("sample")
public class SampleProperties {
private Map<String, Integer> contexts;
// @fold:on // getters/setters ...
public Map<String, Integer> getContexts() {
return this.contexts;
}
public void setContexts(Map<String, Integer> contexts) {
this.contexts = contexts;
}
// @fold:off
}
/*
* 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.deployment.cloud.cloudfoundry.bindingtoservices;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
class MyBean implements EnvironmentAware {
@SuppressWarnings("unused")
private String instanceId;
@Override
public void setEnvironment(Environment environment) {
this.instanceId = environment.getProperty("vcap.application.instance_id");
}
// ...
}
/*
* 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.devtools.restart.disable;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
System.setProperty("spring.devtools.restart.enabled", "false");
SpringApplication.run(MyApplication.class, args);
}
}
/*
* 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.gettingstarted.firstapplication.code;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
public class Example {
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) {
SpringApplication.run(Example.class, args);
}
}
/*
* 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.howto.dataaccess.configurecustomdatasource;
public class FancyDataSource {
}
/*
* 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.howto.dataaccess.configurecustomdatasource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
public class FancyDataSourceConfiguration {
@Bean
@ConfigurationProperties(prefix = "app.datasource")
public FancyDataSource dataSource() {
return new FancyDataSource();
}
}
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.boot.docs.howto.dataaccess.configurehibernatenamingstrategy; package org.springframework.boot.docs.howto.dataaccess.configurehibernatenamingstrategy.spring;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
...@@ -22,11 +22,11 @@ import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; ...@@ -22,11 +22,11 @@ import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@Configuration @Configuration(proxyBeanMethods = false)
class CaseSensitiveSpringPhysicalNamingStrategyConfiguration { public class MyHibernateConfiguration {
@Bean @Bean
SpringPhysicalNamingStrategy caseSensitivePhysicalNamingStrategy() { public SpringPhysicalNamingStrategy caseSensitivePhysicalNamingStrategy() {
return new SpringPhysicalNamingStrategy() { return new SpringPhysicalNamingStrategy() {
@Override @Override
......
/*
* 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.howto.dataaccess.configurehibernatenamingstrategy.standard;
import org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
class MyHibernateConfiguration {
@Bean
PhysicalNamingStrategyStandardImpl caseSensitivePhysicalNamingStrategy() {
return new PhysicalNamingStrategyStandardImpl();
}
}
/*
* 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.howto.dataaccess.separateentitydefinitionsfromspringconfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@EntityScan(basePackageClasses = City.class)
public class Application {
// ...
}
/*
* 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.howto.dataaccess.separateentitydefinitionsfromspringconfiguration;
class City {
}
...@@ -49,7 +49,7 @@ public class CustomEntityManagerFactoryConfiguration { ...@@ -49,7 +49,7 @@ public class CustomEntityManagerFactoryConfiguration {
} }
private JpaVendorAdapter createJpaVendorAdapter(JpaProperties jpaProperties) { private JpaVendorAdapter createJpaVendorAdapter(JpaProperties jpaProperties) {
// Map JPA properties as needed // ... map JPA properties as needed
return new HibernateJpaVendorAdapter(); return new HibernateJpaVendorAdapter();
} }
......
/*
* 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.howto.dataaccess.usemultipleentitymanagers;
public class Customer {
}
/*
* 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.howto.dataaccess.usemultipleentitymanagers;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@Configuration(proxyBeanMethods = false)
@EnableJpaRepositories(basePackageClasses = Customer.class, entityManagerFactoryRef = "secondEntityManagerFactory")
public class CustomerConfiguration {
}
/*
* 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.howto.dataaccess.usemultipleentitymanagers;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@Configuration(proxyBeanMethods = false)
@EnableJpaRepositories(basePackageClasses = Order.class, entityManagerFactoryRef = "firstEntityManagerFactory")
public class OrderConfiguration {
}
/*
* 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.howto.jersey.alongsideanotherwebframework;
class Endpoint {
}
/*
* 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.howto.jersey.alongsideanotherwebframework;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletProperties;
import org.springframework.stereotype.Component;
@Component
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
register(Endpoint.class);
property(ServletProperties.FILTER_FORWARD_ON_404, true);
}
}
/*
* 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.howto.messaging.disabletransactedjmssession;
import javax.jms.ConnectionFactory;
import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
@Configuration(proxyBeanMethods = false)
public class MyJmsConfiguration {
@Bean
public DefaultJmsListenerContainerFactory jmsListenerContainerFactory(ConnectionFactory connectionFactory,
DefaultJmsListenerContainerFactoryConfigurer configurer) {
DefaultJmsListenerContainerFactory listenerFactory = new DefaultJmsListenerContainerFactory();
configurer.configure(listenerFactory, connectionFactory);
listenerFactory.setTransactionManager(null);
listenerFactory.setSessionTransacted(false);
return listenerFactory;
}
}
/*
* 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.howto.propertiesandconfiguration.externalizeconfiguration.application;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(MyApplication.class);
application.setBannerMode(Banner.Mode.OFF);
application.run(args);
}
}
/*
* 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.howto.propertiesandconfiguration.externalizeconfiguration.builder;
import org.springframework.boot.Banner;
import org.springframework.boot.builder.SpringApplicationBuilder;
public class MyApplication {
public static void main(String[] args) {
// @formatter:off
new SpringApplicationBuilder()
.bannerMode(Banner.Mode.OFF)
.sources(MyApplication.class)
.run(args);
// @formatter:on
}
}
/*
* 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.howto.security.enablehttps;
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 MySecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
// Customize the application security ...
http.requiresChannel().anyRequest().requiresSecure();
return http.build();
}
}
/*
* 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.howto.springmvc.writejsonrestservice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@RequestMapping("/thing")
public MyThing thing() {
return new MyThing();
}
}
/*
* 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.howto.springmvc.writejsonrestservice;
public class MyThing {
}
/*
* 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.howto.springmvc.writexmlrestservice;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class MyThing {
private String name;
// @fold:on // getters/setters ...
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
// @fold:off
}
/*
* 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.howto.testcontainers.dynamicproperties;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.Neo4jContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
@SpringBootTest
@Testcontainers
class MyIntegrationTests {
@Container
static Neo4jContainer<?> neo4j = new Neo4jContainer<>("neo4j:4.2");
@Test
void myTest() {
// ...
}
@DynamicPropertySource
static void neo4jProperties(DynamicPropertyRegistry registry) {
registry.add("spring.neo4j.uri", neo4j::getBoltUrl);
}
}
/*
* 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.howto.testcontainers.vanilla;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.Neo4jContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
@Testcontainers
class MyIntegrationTests {
@Container
static Neo4jContainer<?> neo4j = new Neo4jContainer<>("neo4j:4.2");
@Test
void myTest() {
// ...
}
}
/*
* 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.howto.testingwithspringsecurity;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@WebMvcTest(UserController.class)
public class MySecurityTests {
@Autowired
private MockMvc mvc;
@Test
@WithMockUser(roles = "ADMIN")
void requestProtectedUrlWithUser() throws Exception {
this.mvc.perform(get("/"));
}
}
/*
* 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.howto.testingwithspringsecurity;
class UserController {
}
/*
* 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.howto.traditionaldeployment.convertexistingapplication;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
// Customize the application or call application.sources(...) to add sources
// Since our example is itself a @Configuration class (via @SpringBootApplication)
// we actually don't need to override this method.
return application;
}
// tag::main[]
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
// end::main[]
}
/*
* 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.howto.traditionaldeployment.convertexistingapplication.both;
import org.springframework.boot.Banner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return customizerBuilder(builder);
}
public static void main(String[] args) {
customizerBuilder(new SpringApplicationBuilder()).run(args);
}
private static SpringApplicationBuilder customizerBuilder(SpringApplicationBuilder builder) {
return builder.sources(MyApplication.class).bannerMode(Banner.Mode.OFF);
}
}
/*
* 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.howto.traditionaldeployment.war;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MyApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
/*
* 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.howto.traditionaldeployment.weblogic;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.web.WebApplicationInitializer;
@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer implements WebApplicationInitializer {
}
/*
* 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.howto.webserver.addservletfilterlistener.springbean.disable;
import javax.servlet.Filter;
public abstract class MyFilter implements Filter {
}
/*
* 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.howto.webserver.addservletfilterlistener.springbean.disable;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
public class MyFilterConfiguration {
@Bean
public FilterRegistrationBean<MyFilter> registration(MyFilter filter) {
FilterRegistrationBean<MyFilter> registration = new FilterRegistrationBean<>(filter);
registration.setEnabled(false);
return registration;
}
}
/*
* 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.howto.webserver.configure;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;
@Component
public class MyTomcatWebServerCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
@Override
public void customize(TomcatServletWebServerFactory factory) {
// customize the factory here
}
}
/*
* 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.howto.webserver.createwebsocketendpointsusingserverendpoint;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration(proxyBeanMethods = false)
public class MyWebSocketConfiguration {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
/*
* 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.howto.webserver.discoverport;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class MyWebIntegrationTests {
@LocalServerPort
int port;
// ...
}
/*
* 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.using.autoconfiguration.disablingspecific;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class MyApplication {
}
/*
* 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.using.springbeansanddependencyinjection.multipleconstructors;
public interface AccountService {
}
/*
* 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.using.springbeansanddependencyinjection.multipleconstructors;
import java.io.PrintStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class DatabaseAccountService implements AccountService {
@SuppressWarnings("unused")
private final RiskAssessor riskAssessor;
@SuppressWarnings("unused")
private final PrintStream out;
@Autowired
public DatabaseAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
this.out = System.out;
}
public DatabaseAccountService(RiskAssessor riskAssessor, PrintStream out) {
this.riskAssessor = riskAssessor;
this.out = out;
}
// ...
}
/*
* 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.using.springbeansanddependencyinjection.multipleconstructors;
public interface RiskAssessor {
}
/*
* 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.using.springbeansanddependencyinjection.singleconstructor;
public interface AccountService {
}
/*
* 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.using.springbeansanddependencyinjection.singleconstructor;
import org.springframework.stereotype.Service;
@Service
public class DatabaseAccountService implements AccountService {
@SuppressWarnings("unused")
private final RiskAssessor riskAssessor;
public DatabaseAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}
// ...
}
/*
* 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.using.springbeansanddependencyinjection.singleconstructor;
public interface RiskAssessor {
}
/*
* 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.using.structuringyourcode.locatingthemainclass;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
/*
* 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.using.usingthespringbootapplicationannotation.individualannotations;
public class MyAnotherConfig {
}
/*
* 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.using.usingthespringbootapplicationannotation.individualannotations;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@Import({ MyConfig.class, MyAnotherConfig.class })
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
/*
* 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.using.usingthespringbootapplicationannotation.individualannotations;
public class MyConfig {
}
/*
* 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.using.usingthespringbootapplicationannotation.springapplication;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment