栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

利用Spring框架技术的控制反转和依赖注入,实现学生的保存操作

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

利用Spring框架技术的控制反转和依赖注入,实现学生的保存操作

要求:假设通过StudentController、StudentService和StudentDao等类和接口完成学生的保存操作,请编程实现相关的接口和类,要求采用Spring框架技术中提供的控制反转和依赖注入的松耦合编程方法,使用基于Annotation的Bean装配方法来实现相关组件的生成,写出测试程序,运行查看其结果。

要使用Spring框架对类和对象进行管理,关键在于配置环境
1、导入所需要的jar包
将Spring的四个核心包,一个依赖包,还有实现包扫描需要用到的aop的包复制到lib目录下

2、StudentDao接口

package experiment01;

public interface StudentDao {
	public void save();
}

3、StudentDaoImpl实现类

package experiment01;

import org.springframework.stereotype.Repository;

@Repository("studentDao")
public class StudentDaoImpl implements StudentDao{
	public void save(){
		System.out.println("studentDao...save...");
	}
}

4、StudentService接口

package experiment01;

public interface StudentService {
	public void save();
}

5、StudentServiceImpl实现类

package experiment01;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

@Service("studentService")
public class StudentServiceImpl implements StudentService{
	
	@Resource(name="studentDao")
	StudentDao studentDao;
	
	public void save(){
		this.studentDao.save();
		System.out.println("studentService...save...");
	}
}

6、StudentController控制器类

package experiment01;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller("studentController")
public class StudentController {
	
	@Autowired
	StudentService studentService;
	
	public void save(){
		this.studentService.save();
		System.out.println("studentController...save...");
	}
}

7、配置文件beans.xml



    
    
    
    
    
    	
    	
    	
    
    
 	

8、编写测试类

package experiment01;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AnnotationTest {

	public static void main(String[] args) {
		//定义配置文件的路径;
		String xmlPath="experiment01/beans1.xml";
		//创建Spring的ApplicationContext容器;
		ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
		//通过获取容器内的bean得到StudentController对象;
		StudentController studentController=(StudentController)applicationContext.getBean("studentController");
		//调用StudentController对象的方法;
		studentController.save();
		
	}

}

运行结果:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/684973.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号