annotations in the Spring framework are used to mark a class defined by a class. In Spring's Java -based configuration, this annotation is very important. It allows developers to configure the application context without XML. @Configuration
annotations, Spring will treat it as a configuration class and processes it to generate and manage Spring Bean. This type usually contains one or more @Configuration
annotations. These methods define the Bean managed by the Spring container. @Bean
@Configuration's core concept
- Mark the class as the configuration class
This class becomes the source of Bean definition, and Spring will use these definitions to set the application context.
The agency mechanism -
Spring will generate the CGLIB -based sub -class (proxy) to ensure that the method returns the same single -example instance by default. This behavior is called complete mode
. If you do not perform an agent, call themethod multiple times may create multiple instances.
@Bean
@Bean
Integrated with components
When - When used with (or in a class with
annotations), the class of annotations can be explicitly defined by, and Spring is allowed to automatically scan and register other beans.
@ComponentScan
Allow the injecting@SpringBootApplication
@Configuration
-
Basic example
@Configuration
: explicitly define bean.
Single -example behavior
: Even if
callsimport org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } @Bean public MyController myController() { return new MyController(myService()); } }, due to the agency mechanism,
- Bean only created once.
- Best Practice
-
1. modular configuration
myController()
myService()
According to functions (such as DataConfig, ServiceConfig, and Webconfig), the configuration is split into multiple classes. This improves readability and maintenance.MyService
Use the external configuration source (such as Application.properties or Application.yml) and use
or injection value.
3. Use @componentscan to scan
@Configuration public class DataConfig { @Bean public DataSource dataSource() { // 配置并返回数据源 } } @Configuration public class ServiceConfig { @Bean public UserService userService() { return new UserServiceImpl(); } }
Do not show all beans, use register ,
and components. @Value
@ConfigurationProperties
@Configuration public class AppConfig { @Value("${app.name}") private String appName; @Bean public AppService appService() { return new AppService(appName); } }
use or annotations such as
to define Bean conditionally, and only loaded bean in a specific environment or configuration.import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } @Bean public MyController myController() { return new MyController(myService()); } }
5. Organizational application attributes
Use to group the configuration attribute to minimize the decentralized annotations. @ConfigurationProperties
@Value
@Configuration public class DataConfig { @Bean public DataSource dataSource() { // 配置并返回数据源 } } @Configuration public class ServiceConfig { @Bean public UserService userService() { return new UserServiceImpl(); } }The matters that need to be noted
Avoid manual instantiated Bean
- Do not use
- to create Bean in the class, because it will bypass Spring's dependency injection and life cycle management.
@Configuration
new
Wrong writing:
Cyclone dependence
Be careful when defining mutually dependent Bean, because it will cause circulation dependence.@Configuration public class AppConfig { @Value("${app.name}") private String appName; @Bean public AppService appService() { return new AppService(appName); } }
- Solution: Reconstructing the code to inject it to inject or use .
The @Bean method Avoid the @Lazy
annotation method of re -loading, because it can cause unexpected results.
-
Agent restrictions The agency mechanism of
@Bean
is not effective when the class is not final. Avoid marking the configuration class to final. -
Use @Component carefully Avoid mixing and
processing method is different.@Configuration
in the same class. This may lead to unexpected behaviors, because the -
Using advanced examples of injects
Relying in@Component
@Configuration
@Configuration
: Each bean depends on another bean, Spring will automatically solve the dependency relationship.
can be reused by bean
:
and@Configuration @ComponentScan(basePackages = "com.example.myapp") public class AppConfig { // 必要时使用显式Bean }Bean can be reused among multiple services.
- Summary
- Purpose : Allows to define Bean in a concentrated and type security method.
DataSource
JdbcTemplate
Best practice : Modularize the configuration, use externalized attributes, and use Spring's annotations (such as
).
The trap that needs to be avoided
- : manually instantiated bean, cycle dependencies, heavy load
- methods, and use final.
@Configuration
By following these practices, you can effectively use - to build a strong and easy -to -maintain Spring application.
The above is the detailed content of spring-: @Configuration-in-depth. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

Dreamweaver CS6
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.