Two solutions configured by Spring Boot
@SpringBootConfiguration
Automatic configuration (@EnableAutoConfiguration
Choose depends on the specific needs of the project.
Use scene | Method | Cause |
---|---|---|
Need to completely control bean and configuration | > | Manually define all content (just like in the classic Spring project). |
Nepring boot automatic configuration commonly used components | > | Save time by automatically configure Bean based on dependencies. |
You need to use two methods at the same time | Both methods are used | The automatic configuration has been enabled, but the manual configuration will cover the default value. |
need to use specific configuration test Spring Boot applications | > | can be used to use a custom test configuration for unit testing. |
Need to disable or adjust automatic configuration | @Enclude = {DataSourceAutoConfiguration.class}) |
Disable specific automatic configurations as needed. |
<code class="language-java">@SpringBootConfiguration public class MyAppConfig { @Bean public DataSource dataSource() { return new HikariDataSource(); // 手动配置数据库 } }</code>
<code class="language-java">@SpringBootApplication // 包含 @EnableAutoConfiguration public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } }</code>
Manual Bean (
) Prefer to be automatically configured.<code class="language-java">@SpringBootApplication public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } } @Configuration class ManualConfig { @Bean public DataSource dataSource() { return new HikariDataSource(); // 覆盖默认自动配置的 DataSource } }</code>
dataSource
Summary
Yes, Spring Boot provides two solutions to solve the configuration problem. The best choice depends on the project's needs: For completely controlling
, use@EnableAutoConfiguration
The above is the detailed content of spring-: configuration-with-two-out-of-the-box-solutions. For more information, please follow other related articles on the PHP Chinese website!