一、 什么是java bean
1、所有屬性為private
2、提供默認構造方法
3、提供getter和setter
4、實現serializable接口
5、放回對象為一個對象的方法
二、實現注冊bean的方法
- 使用的注解
在類上使用 @configuration
方法上使用 @bean
代碼實現
參考文章@bean 中的name屬性
@bean(name = "book1")
public Book book() {
return new Book;
}
@bean(name = "book2")
public Book book() {
return new Book;
}
- Book 類
public class Book {
private String name;
private String type;
private BigDecimal price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
}
name 屬性就相當于是xml配置bean時的id屬性
- bean 的注入(使用)
@Autowired
@Qualifier(value = "book1")
private Book book;
因為在該系統中有不止一個Book類型的book()bean
所有使用@Qualifier(value = "book1")指明使用哪個bean