search
HomeJavajavaTutorialspring-: @Configuration-in-depth

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());
    }
}
, 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();
    }
}

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);
    }
}

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
  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);
    }
}
  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
}
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
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
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

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 Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools