Extract code samples from docs
See gh-6313
This commit is contained in:
@@ -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:
|
||||
|
||||
[source,java,pending-extract=true,indent=0]
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests((requests) ->
|
||||
requests.anyRequest().hasRole("ENDPOINT_ADMIN"));
|
||||
http.httpBasic();
|
||||
return http.build();
|
||||
}
|
||||
include::{docs-java}/actuator/endpoints/security/typical/MySecurityConfiguration.java[]
|
||||
----
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests((requests) ->
|
||||
requests.anyRequest().permitAll());
|
||||
return http.build();
|
||||
}
|
||||
include::{docs-java}/actuator/endpoints/security/exposeall/MySecurityConfiguration.java[]
|
||||
----
|
||||
|
||||
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
|
||||
The `Health` response should include a status and can optionally include additional details to be displayed.
|
||||
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;
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
include::{docs-java}/actuator/endpoints/health/writingcustomhealthindicators/MyHealthIndicator.java[]
|
||||
----
|
||||
|
||||
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
|
||||
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:
|
||||
|
||||
[source,java,pending-extract=true,indent=0]
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@Component
|
||||
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()));
|
||||
}
|
||||
|
||||
}
|
||||
include::{docs-java}/actuator/endpoints/health/reactivehealthindicators/MyReactiveHealthIndicator.java[]
|
||||
----
|
||||
|
||||
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
|
||||
|
||||
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;
|
||||
|
||||
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"));
|
||||
}
|
||||
|
||||
}
|
||||
include::{docs-java}/actuator/endpoints/info/writingcustominfocontributors/MyInfoContributor.java[]
|
||||
----
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
|
||||
return registry -> registry.config().commonTags("region", "us-east-1");
|
||||
}
|
||||
include::{docs-java}/actuator/metrics/gettingstarted/commontags/MyMeterRegistryConfiguration.java
|
||||
----
|
||||
|
||||
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
|
||||
MeterRegistryCustomizer<GraphiteMeterRegistry> graphiteMetricsNamingConvention() {
|
||||
return registry -> registry.config().namingConvention(MY_CUSTOM_CONVENTION);
|
||||
}
|
||||
include::{docs-java}/actuator/metrics/gettingstarted/specifictype/MyMeterRegistryConfiguration.java
|
||||
----
|
||||
|
||||
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
|
||||
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:
|
||||
|
||||
[source,java,pending-extract=true,indent=0]
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@Bean
|
||||
public GraphiteMeterRegistry graphiteMeterRegistry(GraphiteConfig config, Clock clock) {
|
||||
return new GraphiteMeterRegistry(config, clock, MY_HIERARCHICAL_MAPPER);
|
||||
}
|
||||
include::{docs-java}/actuator/metrics/export/graphite/MyGraphiteConfiguration.java
|
||||
----
|
||||
|
||||
|
||||
@@ -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`.
|
||||
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
|
||||
public JmxMeterRegistry jmxMeterRegistry(JmxConfig config, Clock clock) {
|
||||
return new JmxMeterRegistry(config, clock, MY_HIERARCHICAL_MAPPER);
|
||||
}
|
||||
include::{docs-java}/actuator/metrics/export/jmx/MyJmxConfiguration.java
|
||||
----
|
||||
|
||||
|
||||
@@ -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`:
|
||||
|
||||
[source,java,pending-extract=true,indent=0]
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@RestController
|
||||
@Timed
|
||||
public class MyController {
|
||||
|
||||
@GetMapping("/api/addresses")
|
||||
public List<Person> listAddress() { ... }
|
||||
|
||||
@GetMapping("/api/people")
|
||||
public List<Person> listPeople() { ... }
|
||||
|
||||
}
|
||||
include::{docs-java}/actuator/metrics/supported/timedannotation/all/MyController.java[]
|
||||
----
|
||||
|
||||
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
|
||||
public class MyController {
|
||||
|
||||
@GetMapping("/api/addresses")
|
||||
public List<Person> listAddress() { ... }
|
||||
|
||||
@GetMapping("/api/people")
|
||||
@Timed
|
||||
public List<Person> listPeople() { ... }
|
||||
|
||||
}
|
||||
include::{docs-java}/actuator/metrics/supported/timedannotation/single/MyController.java[]
|
||||
----
|
||||
|
||||
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
|
||||
@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() { ... }
|
||||
|
||||
}
|
||||
include::{docs-java}/actuator/metrics/supported/timedannotation/change/MyController.java[]
|
||||
----
|
||||
|
||||
NOTE: A `@Timed` annotation with `longTask = true` will enable a long task timer for the method.
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
:github-issues: https://github.com/{github-repo}/issues/
|
||||
:github-wiki: https://github.com/{github-repo}/wiki
|
||||
: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-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
|
||||
|
||||
@@ -37,15 +37,7 @@ An exception is thrown if more than one candidate is found.
|
||||
=== Example 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);
|
||||
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));
|
||||
}
|
||||
});
|
||||
include::{docs-java}/buildtoolplugins/otherbuildsystems/examplerepackageimplementation/MyBuildTool.java[]
|
||||
----
|
||||
|
||||
@@ -59,15 +59,7 @@ The following example shows a "`hello world`" web application written in Groovy:
|
||||
.hello.groovy
|
||||
[source,groovy,indent=0,subs="verbatim,quotes,attributes"]
|
||||
----
|
||||
@RestController
|
||||
class WebApplication {
|
||||
|
||||
@RequestMapping("/")
|
||||
String home() {
|
||||
"Hello World!"
|
||||
}
|
||||
|
||||
}
|
||||
include::{docs-groovy}/cli/usingthecli/run/WebApplication.groovy[tag=*]
|
||||
----
|
||||
|
||||
To compile and run the application, type the following command:
|
||||
@@ -185,17 +177,16 @@ For example, consider the following declaration:
|
||||
|
||||
[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/`.
|
||||
|
||||
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",
|
||||
"com.example.another-bom:1.0.0"])
|
||||
include::{docs-groovy}/cli/usingthecli/run/customdependencymanagement/multiple/CustomDependencyManagement.groovy[tag=*]
|
||||
----
|
||||
|
||||
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 `@
|
||||
|
||||
Consider the following example:
|
||||
|
||||
[source,java,pending-extract=true,indent=0,subs="verbatim,attributes"]
|
||||
[source,java,indent=0,subs="verbatim,attributes"]
|
||||
----
|
||||
@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;
|
||||
|
||||
// ... getter and setters
|
||||
|
||||
}
|
||||
include::{docs-java}/configurationmetadata/annotationprocessor/automaticmetadatageneration/ServerProperties.java[]
|
||||
----
|
||||
|
||||
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
|
||||
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:
|
||||
|
||||
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"]
|
||||
[source,java,indent=0,subs="verbatim,quotes,attributes"]
|
||||
----
|
||||
@ConfigurationProperties(prefix = "acme.messaging")
|
||||
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
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
include::{docs-java}/configurationmetadata/annotationprocessor/automaticmetadatageneration/MessagingProperties.java[]
|
||||
----
|
||||
|
||||
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
|
||||
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:
|
||||
|
||||
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"]
|
||||
[source,java,indent=0,subs="verbatim,quotes,attributes"]
|
||||
----
|
||||
@ConfigurationProperties(prefix="server")
|
||||
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
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
include::{docs-java}/configurationmetadata/annotationprocessor/automaticmetadatageneration/nestedproperties/ServerProperties.java[]
|
||||
----
|
||||
|
||||
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
|
||||
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:
|
||||
|
||||
[source,java,pending-extract=true,indent=0]
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@ConfigurationProperties("app.acme")
|
||||
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);
|
||||
}
|
||||
}
|
||||
include::{docs-java}/configurationmetadata/format/group/AcmeProperties.java[]
|
||||
----
|
||||
|
||||
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
|
||||
|
||||
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")
|
||||
public class SampleProperties {
|
||||
|
||||
private Map<String,Integer> contexts;
|
||||
// getters and setters
|
||||
}
|
||||
include::{docs-java}/configurationmetadata/manualhints/valuehint/SampleProperties.java[]
|
||||
----
|
||||
|
||||
The magic values are (in this example) are `sample1` and `sample2`.
|
||||
|
||||
@@ -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:
|
||||
|
||||
[source,java,pending-extract=true,indent=0]
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@Component
|
||||
class MyBean implements EnvironmentAware {
|
||||
|
||||
private String instanceId;
|
||||
|
||||
@Override
|
||||
public void setEnvironment(Environment environment) {
|
||||
this.instanceId = environment.getProperty("vcap.application.instance_id");
|
||||
}
|
||||
|
||||
// ...
|
||||
|
||||
}
|
||||
include::{docs-java}/deployment/cloud/cloudfoundry/bindingtoservices/MyBean.java[]
|
||||
----
|
||||
|
||||
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
|
||||
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:
|
||||
|
||||
[source,java,pending-extract=true,indent=0]
|
||||
[source,java,indent=0]
|
||||
----
|
||||
import org.springframework.boot.*;
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
include::{docs-java}/gettingstarted/firstapplication/code/Example.java[]
|
||||
----
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
@ConfigurationProperties(prefix="app.datasource")
|
||||
public DataSource dataSource() {
|
||||
return new FancyDataSource();
|
||||
}
|
||||
include::{docs-java}/howto/dataaccess/configurecustomdatasource/FancyDataSourceConfiguration.java[]
|
||||
----
|
||||
|
||||
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].
|
||||
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:
|
||||
|
||||
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"]
|
||||
[source,java,indent=0,subs="verbatim,quotes,attributes"]
|
||||
----
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableAutoConfiguration
|
||||
@EntityScan(basePackageClasses=City.class)
|
||||
public class Application {
|
||||
|
||||
//...
|
||||
|
||||
}
|
||||
include::{docs-java}/howto/dataaccess/separateentitydefinitionsfromspringconfiguration/Application.java[]
|
||||
----
|
||||
|
||||
|
||||
@@ -255,7 +244,7 @@ This implementation provides the same table structure as Hibernate 4: all dots a
|
||||
|
||||
[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:
|
||||
@@ -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:
|
||||
|
||||
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"]
|
||||
[source,java,indent=0,subs="verbatim,quotes,attributes"]
|
||||
----
|
||||
@Bean
|
||||
public PhysicalNamingStrategy physicalNamingStrategy() {
|
||||
return new PhysicalNamingStrategyStandardImpl();
|
||||
}
|
||||
include::{docs-java}/howto/dataaccess/configurehibernatenamingstrategy/standard/MyHibernateConfiguration.java[]
|
||||
----
|
||||
|
||||
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
|
||||
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:
|
||||
|
||||
[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[]
|
||||
----
|
||||
@@ -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.
|
||||
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)
|
||||
@EnableJpaRepositories(basePackageClasses = Customer.class,
|
||||
entityManagerFactoryRef = "secondEntityManagerFactory")
|
||||
public class CustomerConfiguration {
|
||||
...
|
||||
}
|
||||
[source,java,indent=0,subs="verbatim,quotes,attributes"]
|
||||
----
|
||||
include::{docs-java}/howto/dataaccess/usemultipleentitymanagers/CustomerConfiguration.java[]
|
||||
----
|
||||
|
||||
|
||||
|
||||
@@ -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`.
|
||||
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
|
||||
public class JerseyConfig extends ResourceConfig {
|
||||
|
||||
public JerseyConfig() {
|
||||
register(Endpoint.class);
|
||||
property(ServletProperties.FILTER_FORWARD_ON_404, true);
|
||||
}
|
||||
|
||||
}
|
||||
include::{docs-java}/howto/jersey/alongsideanotherwebframework/JerseyConfig.java[]
|
||||
----
|
||||
|
||||
@@ -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 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
|
||||
public DefaultJmsListenerContainerFactory jmsListenerContainerFactory(
|
||||
ConnectionFactory connectionFactory,
|
||||
DefaultJmsListenerContainerFactoryConfigurer configurer) {
|
||||
DefaultJmsListenerContainerFactory listenerFactory =
|
||||
new DefaultJmsListenerContainerFactory();
|
||||
configurer.configure(listenerFactory, connectionFactory);
|
||||
listenerFactory.setTransactionManager(null);
|
||||
listenerFactory.setSessionTransacted(false);
|
||||
return listenerFactory;
|
||||
}
|
||||
include::{docs-java}/howto/messaging/disabletransactedjmssession/MyJmsConfiguration.java[]
|
||||
----
|
||||
|
||||
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
|
||||
|
||||
[[howto.properties-and-configuration.externalize-configuration]]
|
||||
=== 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.*+`.
|
||||
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.
|
||||
|
||||
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`.
|
||||
Consider the following application:
|
||||
Properties defined in external configuration override and replace the values specified with the Java API, with the notable exception of the primary sources.
|
||||
Primary sources are those provided to the `SpringApplication` constructor:
|
||||
|
||||
[source,java,pending-extract=true,indent=0]
|
||||
[source,java,indent=0]
|
||||
----
|
||||
new SpringApplicationBuilder()
|
||||
.bannerMode(Banner.Mode.OFF)
|
||||
.sources(demo.MyApp.class)
|
||||
.run(args);
|
||||
include::{docs-java}/howto/propertiesandconfiguration/externalizeconfiguration/application/MyApplication.java[]
|
||||
----
|
||||
|
||||
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]
|
||||
----
|
||||
spring:
|
||||
main:
|
||||
sources: "com.acme.Config,com.acme.ExtraConfig"
|
||||
sources: "com.example.MyDatabaseConfig,com.example.MyJmsConfig"
|
||||
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
|
||||
|
||||
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
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
// Customize the application security
|
||||
http.requiresChannel().anyRequest().requiresSecure();
|
||||
return http.build();
|
||||
}
|
||||
include::{docs-java}/howto/security/enablehttps/MySecurityConfig.java[]
|
||||
----
|
||||
|
||||
@@ -10,17 +10,9 @@ This section answers common questions about Spring MVC and Spring Boot.
|
||||
=== 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:
|
||||
|
||||
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"]
|
||||
[source,java,indent=0,subs="verbatim,quotes,attributes"]
|
||||
----
|
||||
@RestController
|
||||
public class MyController {
|
||||
|
||||
@RequestMapping("/thing")
|
||||
public MyThing thing() {
|
||||
return new MyThing();
|
||||
}
|
||||
|
||||
}
|
||||
include::{docs-java}/howto/springmvc/writejsonrestservice/MyController.java[]
|
||||
----
|
||||
|
||||
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:
|
||||
|
||||
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
|
||||
public class MyThing {
|
||||
private String name;
|
||||
// .. getters and setters
|
||||
}
|
||||
include::{docs-java}/howto/springmvc/writexmlrestservice/MyThing.java[]
|
||||
----
|
||||
|
||||
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
|
||||
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:
|
||||
|
||||
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"]
|
||||
[source,java,indent=0,subs="verbatim,quotes,attributes"]
|
||||
----
|
||||
@SpringBootTest
|
||||
@Testcontainers
|
||||
class ExampleIntegrationTests {
|
||||
|
||||
@Container
|
||||
static Neo4jContainer<?> neo4j = new Neo4jContainer<>();
|
||||
|
||||
}
|
||||
include::{docs-java}/howto/testcontainers/vanilla/MyIntegrationTests.java
|
||||
----
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
@Testcontainers
|
||||
class ExampleIntegrationTests {
|
||||
|
||||
@Container
|
||||
static Neo4jContainer<?> neo4j = new Neo4jContainer<>();
|
||||
|
||||
@DynamicPropertySource
|
||||
static void neo4jProperties(DynamicPropertyRegistry registry) {
|
||||
registry.add("spring.neo4j.uri", neo4j::getBoltUrl);
|
||||
}
|
||||
|
||||
}
|
||||
include::{docs-java}/howto/testcontainers/dynamicproperties/MyIntegrationTests.java
|
||||
----
|
||||
|
||||
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 @@
|
||||
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.
|
||||
|
||||
[source,java,pending-extract=true,indent=0]
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@Test
|
||||
@WithMockUser(roles="ADMIN")
|
||||
public void requestProtectedUrlWithUser() throws Exception {
|
||||
mvc
|
||||
.perform(get("/"))
|
||||
...
|
||||
}
|
||||
include::{docs-java}/howto/testingwithspringsecurity/MySecurityTests.java[]
|
||||
----
|
||||
|
||||
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
|
||||
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:
|
||||
|
||||
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"]
|
||||
[source,java,indent=0,subs="verbatim,quotes,attributes"]
|
||||
----
|
||||
@SpringBootApplication
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
include::{docs-java}/howto/traditionaldeployment/war/MyApplication.java[]
|
||||
----
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
include::{docs-java}/howto/traditionaldeployment/convertexistingapplication/MyApplication.java[tag=!main]
|
||||
----
|
||||
|
||||
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
|
||||
|
||||
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) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
include::{docs-java}/howto/traditionaldeployment/convertexistingapplication/MyApplication.java[tag=main]
|
||||
----
|
||||
|
||||
[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:
|
||||
|
||||
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"]
|
||||
[source,java,indent=0,subs="verbatim,quotes,attributes"]
|
||||
----
|
||||
@SpringBootApplication
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
include::{docs-java}/howto/traditionaldeployment/convertexistingapplication/both/MyApplication.java[]
|
||||
----
|
||||
====
|
||||
|
||||
@@ -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:
|
||||
|
||||
[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;
|
||||
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
|
||||
import org.springframework.web.WebApplicationInitializer;
|
||||
|
||||
@SpringBootApplication
|
||||
public class MyApplication extends SpringBootServletInitializer implements WebApplicationInitializer {
|
||||
|
||||
}
|
||||
include::{docs-java}/howto/traditionaldeployment/weblogic/MyApplication.java[]
|
||||
----
|
||||
|
||||
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`
|
||||
|
||||
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)
|
||||
public class MyWebIntegrationTests {
|
||||
|
||||
@LocalServerPort
|
||||
int port;
|
||||
|
||||
// ...
|
||||
|
||||
}
|
||||
include::{docs-java}/howto/webserver/discoverport/MyWebIntegrationTests.java[]
|
||||
----
|
||||
|
||||
[NOTE]
|
||||
@@ -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):
|
||||
|
||||
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"]
|
||||
[source,java,indent=0,subs="verbatim,quotes,attributes"]
|
||||
----
|
||||
@Component
|
||||
public class MyTomcatWebServerCustomizer
|
||||
implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
|
||||
|
||||
@Override
|
||||
public void customize(TomcatServletWebServerFactory factory) {
|
||||
// customize the factory here
|
||||
}
|
||||
}
|
||||
include::{docs-java}/howto/webserver/configure/MyTomcatWebServerCustomizer.java[]
|
||||
----
|
||||
|
||||
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
|
||||
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:
|
||||
|
||||
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"]
|
||||
[source,java,indent=0,subs="verbatim,quotes,attributes"]
|
||||
----
|
||||
@Bean
|
||||
public FilterRegistrationBean registration(MyFilter filter) {
|
||||
FilterRegistrationBean registration = new FilterRegistrationBean(filter);
|
||||
registration.setEnabled(false);
|
||||
return registration;
|
||||
}
|
||||
include::{docs-java}/howto/webserver/addservletfilterlistener/springbean/disable/MyFilterConfiguration.java[]
|
||||
----
|
||||
|
||||
|
||||
@@ -520,12 +499,9 @@ include::{docs-java}/howto/webserver/enablemultiplelistenersinundertow/UndertowM
|
||||
=== 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:
|
||||
|
||||
[source,java,pending-extract=true,indent=0,subs="verbatim,quotes,attributes"]
|
||||
[source,java,indent=0,subs="verbatim,quotes,attributes"]
|
||||
----
|
||||
@Bean
|
||||
public ServerEndpointExporter serverEndpointExporter() {
|
||||
return new ServerEndpointExporter();
|
||||
}
|
||||
include::{docs-java}/howto/webserver/createwebsocketendpointsusingserverendpoint/MyWebSocketConfiguration.java[]
|
||||
----
|
||||
|
||||
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
|
||||
=== 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:
|
||||
|
||||
[source,java,pending-extract=true,indent=0]
|
||||
[source,java,indent=0]
|
||||
----
|
||||
import org.springframework.boot.autoconfigure.*;
|
||||
import org.springframework.boot.autoconfigure.jdbc.*;
|
||||
|
||||
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
|
||||
public class MyApplication {
|
||||
}
|
||||
include::{docs-java}/using/autoconfiguration/disablingspecific/MyApplication.java[]
|
||||
----
|
||||
|
||||
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
|
||||
|
||||
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) {
|
||||
System.setProperty("spring.devtools.restart.enabled", "false");
|
||||
SpringApplication.run(MyApp.class, args);
|
||||
}
|
||||
include::{docs-java}/devtools/restart/disable/MyApplication.java[]
|
||||
----
|
||||
|
||||
|
||||
|
||||
@@ -1,51 +1,23 @@
|
||||
[[using.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.
|
||||
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.
|
||||
|
||||
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;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// ...
|
||||
|
||||
}
|
||||
include::{docs-java}/using/springbeansanddependencyinjection/singleconstructor/DatabaseAccountService.java[]
|
||||
----
|
||||
|
||||
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
|
||||
public class DatabaseAccountService implements AccountService {
|
||||
|
||||
private final RiskAssessor riskAssessor;
|
||||
|
||||
public DatabaseAccountService(RiskAssessor riskAssessor) {
|
||||
this.riskAssessor = riskAssessor;
|
||||
}
|
||||
|
||||
// ...
|
||||
|
||||
}
|
||||
include::{docs-java}/using/springbeansanddependencyinjection/multipleconstructors/DatabaseAccountService.java[]
|
||||
----
|
||||
|
||||
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:
|
||||
com
|
||||
+- example
|
||||
+- myapplication
|
||||
+- Application.java
|
||||
+- MyApplication.java
|
||||
|
|
||||
+- customer
|
||||
| +- Customer.java
|
||||
@@ -46,21 +46,9 @@ The following listing shows a typical layout:
|
||||
+- 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;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
include::{docs-java}/using/structuringyourcode/locatingthemainclass/MyApplication.java[]
|
||||
----
|
||||
|
||||
@@ -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>>)
|
||||
* `@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;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
include::{docs-java}/using/usingthespringbootapplicationannotation/springapplication/MyApplication.java[]
|
||||
----
|
||||
|
||||
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
|
||||
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:
|
||||
|
||||
[source,java,pending-extract=true,indent=0]
|
||||
[source,java,indent=0]
|
||||
----
|
||||
package com.example.myapplication;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
include::{docs-java}/using/usingthespringbootapplicationannotation/individualannotations/MyApplication.java[]
|
||||
----
|
||||
|
||||
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`).
|
||||
|
||||
Reference in New Issue
Block a user