用于注入数据:
作用和XML配置文件中bean标签property标签作用一样
@Autowired
作用自动按照类型注入,只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就注入成功
出现位置:可以是变量上,(set)方法上,属性上等等
- 如果spring容器中没有任何bean类型和注入的变量类型匹配时则报错
- 如果IOC容器中有多个类型匹配时(包括接口类型):
- 如果注入时接口类型的变量名和给定名称的bean对象不一致时则会报错
- 如果注入接口类型的变量名是给定名称的bean对象中的其中一个名称相对应,则spring容器会和当前bean对象匹配注入
测试:
dao接口类:
public interface AccountDao {
void saveAccount();
}
dao实现类:
//使用注解将对象交给spring来管理
@Repository()
public class AccountDaoImpl implements AccountDao{
public void saveAccount() {
System.out.println("AccountDaoImpl保存了数据");
}
}
service业务接口类:
public interface AccountService {
void saveAccount();
}
service接口实现类: