2.Spring IoC容器(控制反转)构造方法注入

package dao;

public interface TestDIDao {
	public void sayHello();
}

package dao;

public class TestDIDaoImpl implements TestDIDao {

	@Override
	public void sayHello() {
		// TODO Auto-generated method stub
		System.out.println("hello");
	}

}

<?xml version="1.0" encoding="UTF-8"?>

<!-- - Application context definition for JPetStore's business layer. - Containsbean 
	references to the transaction manager and to the DAOs in - dataAccessContext-local/jta.xml(see 
	web.xml's "contextConfigLocation"). -->

<beans
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://www.springframework.org/schema/beans">

	<bean id="myTestDIDao" class="dao.TestDIDaoImpl"></bean>
	<!-- 将指定类TestDIDaoImpl配置给Spring,让Spring创建其实例 -->
	<bean id="testDIService" class="service.TestDIServiceImpl">
		<!-- 使用构造方法注入 -->
		<constructor-arg index="0" ref="myTestDIDao" />
		<!-- 将myTestDIDao注入到TestDIServiceImpl类的属性testDIDao上 -->
	</bean>
</beans>
package service;

public interface TestDIService {
	public void sayHello();
}

package service;

import dao.TestDIDao;

public class TestDIServiceImpl implements TestDIService {
	private TestDIDao testDIDao;

	public TestDIServiceImpl(TestDIDao testDIDao) {
		super();
		this.testDIDao = testDIDao;
	}
	// 构造方法,用于实现依赖注入接口对象testDIDao
	
	public void sayHello() {
		testDIDao.sayHello();
		//调用testDIDao中的sayHello方法
		System.out.println("构造方法注入");
	}
}

package test;

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

import service.TestDIService;

public class TestDI {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		ApplicationContext xfc = new ClassPathXmlApplicationContext("applicationContext.xml");
		//初始化Spring容器ApplicationContext,加载配置文件
		TestDIService ts = (TestDIService) xfc.getBean("testDIService");
		//通过容器获取实例,测试构造方法注入
		ts.sayHello();
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值