【汇智学堂】-Spring Ioc(构造方法依赖注入)

控制台查看运行效果:
在这里插入图片描述
文档结构:
在这里插入图片描述
步骤:
创建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

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_39593940/article/details/94463401
今日推荐