控制台查看运行效果:
文档结构:
步骤:
创建dao包内接口与类:
package dao;
public interface TestDao {
public void sayHello();
}
package dao;
public class TestDaoImpl implements TestDao {
@Override
public void sayHello(){
System.out.println("hello springmvc");
}
}
service接口与实现类:
package service;
public interface TestService {
public void sayHello();
}
package service;
import dao.TestDao;
public class TestServiceImpl implements TestService{
private TestDao testDao;
//构造方法,用于实现依赖注入接口对象testDao
public TestServiceImpl(TestDao testDao){
super();
this.testDao=testDao;
}
@Override
public void sayHello(){
testDao.sayHello();
System.out.println("构造方法注入");
}
}
创建测试类:
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.TestService;
public class Test {
public static void main(String[] args){
//初始化Spring容器ApplicationContext,加载配置文件
ApplicationContext appCon=new ClassPathXmlApplicationContext("applicationContext.xml");
TestService ts=(TestService)appCon.getBean("testService");
ts.sayHello();
}
}
applicationContext.xml