The difference between spring @Component and @Bean

@ComponentBoth @Beanare annotations used to define Spring Bean, but their functions and usage are slightly different.

  1. @ComponentAnnotations are used to mark a class as a component in Spring, indicating that this class will be managed by the Spring container and can be used for dependency injection through the container. @ComponentAnnotations can @Autowiredbe used together with other annotations to implement dependency injection. It works for injection of any class, including classes in third-party libraries.

  2. @BeanAnnotations are method-level annotations that tell the Spring container that this method will return an object that should be registered as a Bean and managed by the container. @BeanAnnotations are usually used to configure methods in classes to manually create Bean objects and add them to the Spring container. @BeanAnnotations are often @Configurationused together with to create and configure beans in a Spring application context.

Thus, @Componentannotations are class-level annotations used to mark the class as a Spring component, and @Beanannotations are method-level annotations used to register the object returned by the method as a Spring Bean.

Here is an @Componentexample using annotations:

@Component
public class MyComponent {
    
    
    // ...
}

Here is an @Beanexample using annotations:

@Configuration
public class MyConfiguration {
    
    
    @Bean
    public MyBean myBean() {
    
    
        return new MyBean();
    }
}

In the above example, MyComponentthe class is marked as a Spring component and will be managed by the Spring container. Instead MyConfigurationthe class is marked as a @Beanconfiguration class that contains a method that returns an MyBeanobject and is registered as a bean by the Spring container. -

Guess you like

Origin blog.csdn.net/a772304419/article/details/131330439