gpt4 book ai didi

Spring:@Bean 仍然可以在没有 @Configuration 的情况下工作

转载 作者:行者123 更新时间:2023-12-04 07:18:30 25 4
gpt4 key购买 nike

来自 https://projects.spring.io/spring-framework/我有一个 spring 框架 hellpworld 程序。我删除注释@Configuration .但是程序仍然可以像以前一样运行。为什么?什么是@Configuration在这里扮演什么角色?

最佳答案

您仍然可以使用@Component 标记该类,以便@Bean 实例可用于编程。当你这样做时,它被称为精简模式。在这种模式下,您不能使用 'inter-bean references',这意味着通过方法引用其他实例。

另一方面,带有类 @Configuration 的 @Bean 被包装在侧 cglib 包装器中,可以拦截对此 bean 方法的任何调用,并且可以从上下文返回 bean 实例。意味着您可以使用“ bean 间引用”。

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Bean.html

  • @Configuration 类中的@Bean 方法

  • Typically, @Bean methods are declared within @Configuration classes. In this case, bean methods may reference other @Bean methods in the same class by calling them directly. This ensures that references between beans are strongly typed and navigable. Such so-called 'inter-bean references' are guaranteed to respect scoping and AOP semantics, just like getBean() lookups would. These are the semantics known from the original 'Spring JavaConfig' project which require CGLIB subclassing of each such configuration class at runtime. As a consequence, @Configuration classes and their factory methods must not be marked as final or private in this mode.


  • @Bean 精简模式

  • @Bean methods may also be declared within classes that are not annotated with @Configuration. For example, bean methods may be declared in a @Component class or even in a plain old class. In such cases, a @Bean method will get processed in a so-called 'lite' mode.

    Bean methods in lite mode will be treated as plain factory methods by the container (similar to factory-method declarations in XML), with scoping and lifecycle callbacks properly applied. The containing class remains unmodified in this case, and there are no unusual constraints for the containing class or the factory methods.

    In contrast to the semantics for bean methods in @Configuration classes, 'inter-bean references' are not supported in lite mode. Instead, when one @Bean-method invokes another @Bean-method in lite mode, the invocation is a standard Java method invocation; Spring does not intercept the invocation via a CGLIB proxy.



    和,
    @Configuration 使您能够将许多其他功能与其他注释结合使用

    导入其他配置
    @Import(DatabaseConfig.class)

    资源导入@PropertySource("classpath:config.properties")

    启用组件扫描 @ComponentScan(basePackages = { "com.sample.*"})

    标记配置文件@Profile("生产")

    启用功能@​​Enablexxxx

    http://docs.spring.io/spring-framework/docs/4.0.4.RELEASE/javadoc-api/org/springframework/context/annotation/Configuration.html

    关于Spring:@Bean 仍然可以在没有 @Configuration 的情况下工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40256702/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com