spring的依赖注入及自动装配
1.0、spring的依赖注入
1)setter方式注入实现步骤
IndexDaoImpl类
package com.spring.demo.xml;
public class IndexDaoImpl implements IndexDao{
@Override
public void testDao() {
System.out.println("=======testDao0");
}
}
IndexDaoImpl类
public class IndexServiceImpl implements IndexService{
IndexDao dao1;
@Override
public void testIndexService() {
dao1.testDao();
}
public void setDao0(IndexDao indexDao) {
this.dao1 = indexDao;
}
}
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dao1" class="com.spring.demo.xml.IndexDaoImpl"/>
<!-- <bean id="dao1" class="com.spring.demo.xml.IndexDaoImpl1"/>-->
<bean id="indexService" class="com.spring.demo.xml.IndexServiceImpl">
<property name="dao0" ref="dao1"/>
</bean>
</beans>
test类
public class AutowiredXmlTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext pathXmlApplicationContext = new ClassPathXmlApplicationContext("classpath:spring-origin.xml");
IndexService indexService = (IndexService) pathXmlApplicationContext.getBean("indexService");
indexService.testIndexService();
}
}
2)构造方法注入
被依赖类和test类代码不变,仅依赖类和xml的配置变化
IndexDaoImpl类
public class IndexServiceImpl implements IndexService{
IndexDao dao1;