Table of Contents
: Even if
Do not show all beans, use register ,
:
Home Java javaTutorial spring-: @Configuration-in-depth

spring-: @Configuration-in-depth

Jan 28, 2025 pm 10:06 PM

spring-: @Configuration-in-depth

In -depth understanding of the @Configuration annotation in the Spring framework

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

When a class uses

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

  1. 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.

  2. The agency mechanism
  3. 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 the

    method multiple times may create multiple instances. @Bean @Bean Integrated with components

  4. When
  5. 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

    Class support the dependency injection based on constructor or field -based to solve the dependency item required to create Bean.
  6. Basic example

    @Configuration

    @Bean method
  7. : explicitly define bean.

Single -example behavior

: Even if

calls
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());
    }
}
Copy after login
Copy after login
, 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
2. <免> Avoid hard coding value

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();
    }
}
Copy after login
Copy after login

Do not show all beans, use register ,

and

components. @Value @ConfigurationProperties

4. <条> Use conditions bean
@Configuration
public class AppConfig {

    @Value("${app.name}")
    private String appName;

    @Bean
    public AppService appService() {
        return new AppService(appName);
    }
}
Copy after login
Copy after login

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());
    }
}
Copy after login
Copy after login

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();
    }
}
Copy after login
Copy after login
The matters that need to be noted

<免> Avoid manual instantiated Bean
    Do not use
  1. 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);
    }
}
Copy after login
Copy after login
  1. <决> 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.

  1. <理> Agent restrictions The agency mechanism of @Bean is not effective when the class is not final. Avoid marking the configuration class to final.

  2. <谨> Use @Component carefully Avoid mixing and @Configuration in the same class. This may lead to unexpected behaviors, because the

    processing method is different.
  3. Using advanced examples of injects @Component @Configuration @Configuration

    <赖> Relying in
  4. : 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
}
Copy after login
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
and
).

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

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...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

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...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

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

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

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...

See all articles