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