@Component 和 @Bean 的區別


Spring幫助我們管理Bean分為兩個部分,一個是注冊Bean,一個裝配Bean。
完成這兩個動作有三種方式,一種是使用自動配置的方式、一種是使用JavaConfig的方式,一種就是使用XML配置的方式。

@Compent 作用就相當於 XML配置

@Component
public class Student {
 
    private String name = "lkm";
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
}

@Bean 需要在配置類中使用,即類上需要加上@Configuration注解

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

 

 

那為什么有了@Compent,還需要@Bean呢?
如果你想要將第三方庫中的組件裝配到你的應用中,在這種情況下,是沒有辦法在它的類上添加@Component注解的,因此就不能使用自動化裝配的方案了,但是我們可以使用@Bean,當然也可以使用XML配置。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM