今天我会在spring入门1的基础上,对1中的bean.xml进行改进,采用注解配置,实现与1中同样的功能。
曾经XML的配置:
*
*
用于注入数据的
*
*
用于改变作用范围的
*
和生命周期相关(了解)
*/
配置bean.xml
为了使用注解配置,一定要改变版本信息,如下文件头所示(可以在spring帮助文档中,点击core,ctrl+f查找xmlns:cont,复制看到的版本信息到bean.xml即可)。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在bean.xml的约
束中,而是一个名称为context名称空间和约束中-->
<context:component-scan base-package="com.itheima"></context:component-scan>
</beans>
将类加入容器
我们在要添加到spring容器的类前面加@Component注解,即可将其加入容器。但是你以为这样就行了吗?想多了。spring怎么知道哪个类被注解了呢 ?以我们需要告诉spring到哪里扫描注解。在bean.xml的</context:component-scan>标签中配置base-package属性即可,我们选择com.itheima,就会扫描这个包下所有类上的注解。
@Component
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao = new AccountDaoImpl();
public void saveAccount(){
accountDao.saveAccount();
}
}
当然也可以为上述注解设置一个Id
@Component(value = "AccountService")
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao = new AccountDaoImpl();
public void saveAccount(){
accountDao.saveAccount();
}
}