上篇文章说过,IOC的注入有两个地方需要提供依赖关系,一个是在类中定义,二是在Spring的XML配置文件中需要去定义(描述)。通过使用自动装配,则省去了第二个依赖关系的定义,减少不必要地重复工作。即我们仅仅需要在类中提供依赖关系,继而把对象交给容器管理就可以完成注入。
我们在实际的程序开发过程中,通过Spring XML描述类之间的依赖关系通常是大篇幅的 ,如果使用自动装配则省去了很多配置,极大地提高了开发效率。并且如果对象地依赖关系发生了更新,我们可以不需要去更新依赖关系地配置。
自动装配有4种方式:
- no:不使用自动装配
- byType:根据类型去容器查找并装配
- byName:根据类名去容器查找并装配
- default:等价于no,即不使用自动装配
自动装配的指定方式有两种:
- 全局指定
-
局部指定
全局指定:
即在XML的<beans>标签种添加default-autowire,并指定自动装配的方式,此处代码设置为byType。示例代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
default-autowire="byType">
</beans>
byType:根据类型去容器查找并装配 示例代码如下
package com.tyyd.autowire.dao;
public interface IndexDao {
void test();
}
package com.tyyd.autowire.dao.impl;
import com.tyyd.autowire.dao.IndexDao;
public class IndexDaoImpl implements IndexDao {
public void test() {
System.out.println("IndexDao");
}
}
package com.tyyd.autowire.service;
public interface IndexService {
void test();
}
package com.tyyd.autowire.service.impl;
import com.tyyd.autowire.dao.IndexDao;
import com.tyyd.autowire.service.IndexService;
public class IndexServiceImpl implements IndexService {
private IndexDao indexDao;
public void test() {
indexDao.test();
}
public void setIndexDao(IndexDao indexDao) {
this.indexDao = indexDao;
}
}
package com.tyyd.autowire.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ComponentScan("com.tyyd.autowire")
@ImportResource("classpath:spring.xml")
public class JavaConfig {
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
default-autowire="byType">
<bean id="dao" class="com.tyyd.autowire.dao.impl.IndexDaoImpl"></bean>
<bean id="indexService" class="com.tyyd.autowire.service.impl.In