一、 什么是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