Spring-@Bean & @Component difference

The difference between @Component and @Bean

Spring helps us manage Bean into two parts, one is registration Bean and one assembly Bean.

There are three ways to accomplish these two actions, one is to use automatic configuration, one is to use JavaConfig, and the other is to use XML configuration.

@Compent is equivalent to XML configuration

@Component
public class Student {

    private String name = "lkm";

    public String getName() {
        return name;
    }

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

@Bean needs to be used in the configuration class, that is, the class needs to be annotated with @Configuration

@Configuration
public class WebSocketConfig {

    @Bean
    public Student student(){
        return new Student();
    }
}

Both can be assembled via @Autowired

@Autowired
Student student;

 

Why do you need @Bean when you have @Compent?

If you want to assemble the components in the third-party library into your application, in this case, there is no way to add @Component annotation to its class, so you cannot use the automated assembly solution, but we You can use @Bean, of course, you can also use XML configuration.

 

Why is there a @Bean annotation in Spring?

Annotations fall into two categories

1. One is to use Bean, that is, use the Bean that has been configured in the xml file to complete the assembly of attributes and methods; for example, @Autowired, @Resource, you can pass byTYPE (@Autowired), byNAME (@Resource ) Way to get Bean;

2. One type is registered Bean, @Component, @Repository, @Controller, @Service, @Configration. These annotations are all objects you want to instantiate into a Bean, placed in the IoC container, when you want to use , It will work with @Autowired and @Resource above to perfectly assemble objects, properties and methods.

  • @Bean clearly indicates a method, what method-a method of generating a bean, and handed over to the Spring container management; from this we understand why @Bean is placed on the method annotation, because it is very Explicitly tell the annotated method that you generate a Bean for me and hand it over to the Spring container, and leave the rest to you.
  • Remember, if @Bean is placed on the method, it is a Bean.
Published 952 original articles · praised 1820 · 890,000 views

Guess you like

Origin blog.csdn.net/Dream_Weave/article/details/105394307