Spring的注入依赖(DI)主要有三种注入方式,即构造器注入、Setter注入和使用注解方式;注入依赖可以分为手工装配和自动装配,spring开发团队建议使用手工装配。
今天主要说说构造器注入
基于构造器的DI通过调用带参数的构造器来实现,每个参数代表着一个依赖。
1.持久层 ,spring是基于接口编程的,请注意接口
public class StudentDao implements IStudentDao {
public void saveStudent() {
System.out.println("成功保存一个学生信息");
}
}
2.服务层
public class StudentService implements IStudentService {
private IStudentDao studentDao;
private String id;
public StudentService(IStudentDao studentDao,String id){
this.studentDao = studentDao;
this.id = id;
}
public void saveStudent() {
studentDao.saveStudent();
System.out.print(",ID为:"+id);
}
}
3.spring配置
<bean id="studentDao" class="com.wch.dao.impl.StudentDao"></bean>
<bean id="studentService" class="com.wch.service.impl.StudentService">
<constructor-arg index="0" type="com.wch.dao.IStudentDao" ref="studentDao" />
<constructor-arg index="1" value="123456" type="java.lang.String"></constructor-arg>
</bean>
注:
用'type'属性来显式指定那些构造参数的类型
index属性来显式指定构造参数的索引,从0开始
type="java.lang.String"可以不写
4.经行测试,代码如下
public class TestSpringBuild extends TestCase{
private AbstractApplicationContext ctx = null;
@Before
public void setUp() throws Exception {
//ctx = new ClassPathXmlApplicationContext("bean.xml");
ctx = new FileSystemXmlApplicationContext("classpath:bean.xml");
}
@After
public void tearDown() throws Exception {
ctx.close();
}
@Test public void testBuild(){
StudentService studentService = (StudentService)ctx.getBean("studentService");
studentService.saveStudent();
}
}
分享到:
相关推荐
Spring依赖注入使用构造设注入demo。完整可运行。
黑马程序员-SpringCloud-学习笔记-03-Eureka注册中心
NULL 博文链接:https://zhangyulong.iteye.com/blog/856986
NULL 博文链接:https://coolszy.iteye.com/blog/512193
黑马程序员-SpringCloud-学习笔记01-认识微服务
NULL 博文链接:https://coolszy.iteye.com/blog/510194
黑马程序员-SpringCloud-学习笔记-02-微服务拆分及远程调用
如果需要给该bean提供一些初始化参数,则需要通过依赖注入方式,所谓的 依赖注入就是通过spring将bean所需要的一些参数传递到bean实例对象的过程(将依赖关系注入到对象中) ,spring的依赖注入有3种方式: ...
Spring 学习笔记《依赖注入》源文件。https://blog.csdn.net/jx520/article/details/86549841
Spring2.5.6学习笔记-最新Spring2.5.6学习笔记-最新Spring2.5.6学习笔记-Spring2.5.6学习笔记-最新Spring2.5.6学习笔记-最新Spring2.5.6学习笔记-最新最新
spring-session+spring依赖jar包,包含spring4.0.2.RELEASE相关jar包和commons-pool2-2.4.2.jar,jedis-2.7.3.jar,spring-data-redis-1.6.2.RELEASE.jar,spring-session-1.1.1.RELEASE.jar
Spring Ioc 注解 依赖注入
spring依赖注入底层详解,很不错的资源,欢迎大家来下载学习。
javaEE 开发中 现在最成熟的框架之一应该就是spring了 spring框架最强大的地方就是实现了依赖注入 也叫控制反转 最近的一个项目中用的就是 spring框架 spring框架是工厂模式的应用结合了MVC的设计思想 大家可以...
云的学习笔记-云的学习笔记系统-云的学习笔记系统源码-云的学习笔记管理系统-云的学习笔记管理系统java代码-云的学习笔记系统设计与实现-基于ssm的云的学习笔记系统-基于Web的云的学习笔记系统设计与实现-云的学习...
NULL 博文链接:https://samter.iteye.com/blog/408519
Spring的依赖注入,与前置通知的实例
详解 Spring 3.0 基于 Annotation 的依赖注入实现。。详解 Spring 3.0 基于 Annotation 的依赖注入实现。。
该资源包含了一个利用spring实现的依赖注入的案例,简单易懂。