第一步:在spring的demo2中创建一个CustomerDaoImpl类,模拟实际开发中的dao层
package com.pp.demo2;
public class CustomerDaoImpl {
public void save(){
System.out.println("保存");
}
}
在这里dao层只有一个保存save方法,用来模拟数据库的保存。
第二步:新建CustomerServiceImpl类
package com.pp.demo2;
public class CustomerServiceImpl {
private CustomerDaoImpl dao;
public void setcustomerDao(CustomerDaoImpl dao) {
this.dao = dao;
}
public void save(){
dao.save();
}
}
以上代码,首先创建了一个私有变量,示例化了CustomerDaoImpl,然后使用set方法去构造该该实体类,最后自己创建了一个sava方法去调用实体类dao层的方法。
第三步:配置applicationContext.xml文件
配置applicationContext.xml的意义就是,不用自己去实例化对象,而是通过会话工厂的形式去实例化对象,然后再去拿对象的方法。
<!--依赖注入-->
<bean id="customerDao" class="com.pp.demo2.CustomerDaoImpl"/>
<bean id="customerService" class="com.pp.demo2.CustomerServiceImpl">
<property name="customerDao" ref="customerDao"/>
</bean>
由于原来的service层的类中,含有另外一个实体类。在这里肯定不能向单一的类一样进行配置,所以要进行依赖注入,也就是说,既要配置service层的customerService类,还要配置customerService类中包含的customerDao。因此在配置 在中又加入了这里的name是customerService类中的set方法的方法名,ref与上面的一致,这样就可以链接到一起。
第四步:在demo2包下创建demo.class创建测试类
```java
package com.pp.demo2;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Demo {
@Test
public void run3(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
CustomerServiceImpl bean = (CustomerServiceImpl)context.getBean("customerService");
bean.save();
}
}
在测试类中创建了会话工厂,加载我们的配置文件applicationContext.xml,在通过工厂去拿对象,最后调用对象的方法。
第五步:测试结果
源码地址:https://gitee.com/yangforever/project-learning/tree/master/demo/Spring/