Table of Contents
@Bean 注解方法执行策略 " >@Bean 注解方法执行策略
@Component 注解 " >@Component 注解
示例 1:调用@Configuration类中的@Bean注解的方法,返回的是同一个示例" >示例 1:调用@Configuration类中的@Bean注解的方法,返回的是同一个示例
示例 2 :调用@Component类中的@Bean注解的方法,返回的是一个新的实例。" >示例 2 :调用@Component类中的@Bean注解的方法,返回的是一个新的实例。
Home Java javaTutorial Interviewer: The difference between @Configuration and @Component

Interviewer: The difference between @Configuration and @Component

Aug 15, 2023 pm 04:29 PM
component @configuration

Yesterday, a friend reported to me that he was asked about the annotations @Configuration and @ during the interview. The difference between Component.

In one sentence, all methods with @Bean annotations in @Configuration will be dynamically proxied, so calling this method will return is the same instance.

Understanding: Calling the @Bean annotated method in the @Configuration class returns the same example; while calling the @ in the @Component class The method annotated with Bean returns a new instance.

Note: The call mentioned above is not obtained from the spring container! See the bottom example 1 and example 2

below Take a look at the implementation details.

@Configuration Annotations

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
    String value() default "";
}
Copy after login

From the definition, @ConfigurationAnnotations are essentially @Component, so <context:component-scan/> or @ComponentScan can handle classes annotated with @Configuration.

@ConfigurationThe marked class must meet the following requirements:

  • 配置类必须以类的形式提供(不能是工厂方法返回的实例),允许通过生成子类在运行时增强(cglib 动态代理)。
  • 配置类不能是final 类(没法动态代理)。
  • 配置注解通常为了通过 @Bean注解生成 Spring 容器管理的类,
  • 配置类必须是非本地的(即不能在方法中声明,不能是 private)。
  • 任何嵌套配置类都必须声明为static。
  • @Bean方法可能不会反过来创建进一步的配置类(也就是返回的 bean 如果带有 @Configuration,也不会被特殊处理,只会作为普通的 bean)。

@Bean 注解方法执行策略

先给一个简单的示例代码:

@Configuration
public class MyBeanConfig {

    @Bean
    public Country country(){
        return new Country();
    }

    @Bean
    public UserInfo userInfo(){
        return new UserInfo(country());
    }

}
Copy after login

相信大多数人第一次看到上面 userInfo() 中调用 country()时,会认为这里的 Country和上面 @Bean方法返回的 Country 可能不是同一个对象,因此可能会通过下面的方式来替代这种方式:

  • @Autowired
  • private Country country;

实际上不需要这么做(后面会给出需要这样做的场景),直接调用country() 方法返回的是同一个实例。

@Component 注解

@Component注解并没有通过 cglib 来代理@Bean 方法的调用,因此像下面这样配置时,就是两个不同的 country

@Component
public class MyBeanConfig {

    @Bean
    public Country country(){
        return new Country();
    }

    @Bean
    public UserInfo userInfo(){
        return new UserInfo(country());
    }

}
Copy after login

有些特殊情况下,我们不希望 MyBeanConfig被代理(代理后会变成WebMvcConfig$$EnhancerBySpringCGLIB$$8bef3235293)时,就得用 @Component,这种情况下,上面的写法就需要改成下面这样:

@Component
public class MyBeanConfig {

    @Autowired
    private Country country;

    @Bean
    public Country country(){
        return new Country();
    }

    @Bean
    public UserInfo userInfo(){
        return new UserInfo(country);
    }

}
Copy after login

这种方式可以保证使用的同一个 Country 实例。

示例 1:调用@Configuration类中的@Bean注解的方法,返回的是同一个示例

第一个bean类

package com.xl.test.logtest.utils;

public class Child {
 private String name = "the child";

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
}
Copy after login

第二个bean类

package com.xl.test.logtest.utils;

public class Woman {
 
 private String name = "the woman";
 
 private Child child;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public Child getChild() {
  return child;
 }

 public void setChild(Child child) {
  this.child = child;
 }
}
Copy after login

@Configuration

package com.xl.test.logtest.utils;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Configuration
//@Component
public class Human {
 
 @Bean
 public Woman getWomanBean() {
  Woman woman = new Woman();
  woman.setChild(getChildBean()); // 直接调用@Bean注解的方法方法getChildBean()
  return woman;
 }
 
 @Bean
 public Child getChildBean() {
  return new Child();
 }
}
Copy after login

测试类 I

本测试类为一个配置类,这样启动项目是就可以看到测试效果的,更加快捷;也可以使用其他方式测试见下面的测试类 II

package com.xl.test.logtest.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Man {
 
 @Autowired
 public Man(Woman wn, Child child) {
  System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
  System.out.println(wn.getChild() == child ? "是同一个对象":"不是同一个对象");
 }
}
Copy after login

启动项目,查看输出结果:

Interviewer: The difference between @Configuration and @Component

测试类 II

package com.xl.test.logtest.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xl.test.logtest.utils.Child;
import com.xl.test.logtest.utils.Woman;

@RestController
public class LogTestController {
 @Autowired
 Woman woman ;
 
 @Autowired
 Child child;
 
 @GetMapping("/log")
 public String log() {
  return woman.getChild() == child ? "是同一个对象":"不是同一个对象";
 }
}
Copy after login

浏览器访问项目,查看结果;输入localhost:8080/log

Interviewer: The difference between @Configuration and @Component

示例 2 :调用@Component类中的@Bean注解的方法,返回的是一个新的实例。

测试代码,只需要将@Configuration改为@Component即可!其他的均不变

package com.xl.test.logtest.utils;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

//@Configuration
@Component
public class Human {
 
 @Bean
 public Woman getWomanBean() {
  Woman woman = new Woman();
  woman.setChild(getChildBean()); // 直接调用@Bean注解的方法方法getChildBean()
  return woman;
 }
 
 @Bean
 public Child getChildBean() {
  return new Child();
 }
}
Copy after login

测试 :

Interviewer: The difference between @Configuration and @Component

控制台和浏览器展示,均符合预期!

最后,如果你也需要修改简历,需要模拟面试的。

The above is the detailed content of Interviewer: The difference between @Configuration and @Component. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How vue3 uses defineAsyncComponent and component tags to implement dynamic rendering components How vue3 uses defineAsyncComponent and component tags to implement dynamic rendering components May 12, 2023 pm 05:55 PM

1. Basic dynamic introduction of components: Simple dynamic introduction means that the front end knows which components to introduce, and introduces multiple components into the parent component, but does not render it. After certain conditions are met, it will be rendered at a certain location. specified component. import{reactive,ref,shallowReactive,onActivated,defineAsyncComponent,}from'vue';constcustomModal=defineAsyncComponent(()=>import('./modal/CustomM

Interviewer: The difference between @Configuration and @Component Interviewer: The difference between @Configuration and @Component Aug 15, 2023 pm 04:29 PM

Calling the @Bean annotated method in the @Configuration class returns the same example; calling the @Bean annotated method in the @Component class returns a new instance.

Tips on using mixin, extend, component and other APIs to implement component customization in Vue Tips on using mixin, extend, component and other APIs to implement component customization in Vue Jun 25, 2023 pm 03:28 PM

Vue.js is a popular front-end framework that provides many APIs for component customization. This article will introduce the mixin, extend, component and other APIs in Vue to help you master the skills of component customization. Mixin Mixin is a way to reuse component code in Vue. It allows us to reuse already written code into different components, thereby reducing the need to write duplicate code. For example, we can use mixins to help us combine multiple groups

What are the usage scenarios of @Configuration in Java? What are the usage scenarios of @Configuration in Java? Apr 21, 2023 am 10:37 AM

1. Brief introduction: @Configuration annotation can be annotated on a class. When it is annotated on a class, Spring will automatically scan the class annotated with @Configuration annotation, register it in the IOC container, and instantiate it into a Bean object. If the class annotated with the @Configuration annotation contains a method to create a class object annotated with the @Bean annotation, Spring will also automatically execute the method annotated with the @Bean annotation and register the corresponding Bean definition information to the IOC container. and instantiate it. 2. Annotation description @Configuration annotation is a tool added since Spring 3.0 version.

What to do if react.component reports an error What to do if react.component reports an error Dec 20, 2022 am 10:49 AM

Solution to react.component error: 1. Open the corresponding react file, look for the "class Counter extends Component {static propTypes = {..." statement, and change the equal sign to a colon; 2. Modify "{ "presets": ["react", "es2015", "stage-0"]}" is enough.

Springboot automatic configuration and @Configuration configuration class instance analysis Springboot automatic configuration and @Configuration configuration class instance analysis May 14, 2023 pm 06:25 PM

@Configuration Note Point 1 The configuration class (this class under @Configuration) is actually equivalent to a factory. The method marked with @Bean annotation is equivalent to the factory method. Consider the following example: @Configuration // Note Point 1: The configuration class is actually equivalent to a Factory, the method marked with @Bean annotation is equivalent to the factory method staticclassMyConfig{@BeanpublicBean1bean1(){System.out.println("bean1()");returnnewBean1();} If you want to generate an instance of bean1 in the future

What is the component of react? What is the component of react? Dec 05, 2022 pm 05:54 PM

In react, component means "component" in Chinese, which is an encapsulated UI component with independent functions; the content to be displayed is divided into multiple independent parts, and each such part is a component. Components have two important things, one is properties and the other is state. The properties of a component are given to it by the parent component and store the requirements of the parent component for the child component. The properties can be accessed within the component, but they cannot be modified; the state of the component is defined and used by the component itself for storage. The current state of the component. The state of the component can be modified.

Introduction to Vue.component function and how to register global components Introduction to Vue.component function and how to register global components Jul 25, 2023 pm 10:54 PM

Introduction to the Vue.component function and how to register global components In Vue development, a component is a reusable Vue instance. The concept of components is very useful when we need to use the same UI elements or logic in multiple places. Vue provides the Vue.component function to register global components for use in any Vue instance. This article will introduce the usage of Vue.component function and demonstrate how to register global components. Vue.component function

See all articles