Spring IOC 实现

本文介绍了IOC(Inversion of Control)的概念及其在Spring框架中的应用。通过具体的代码示例展示了如何使用Spring容器管理和创建对象,包括配置文件beans.xml的定义及test.java中的测试用例。

IOC:是一种编程思想,有主动编程变为被动接收

IOC的实现是通过ioc容器来实现,ioc容器-BeanFactory (工厂模式,由spring容器来创建)

beans.xml

ref:引用对象

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
        
	<!-- bean就是java对象,由spring容器创建和管理 -->
	<bean name="hello" class="spring.beans.Hello">
		<property name="name" value="马化腾"></property>
	</bean>
	<bean id="mysqlDao" class="spring.dao.impl.UserDaoMySqlImpl"></bean>
	<bean id="oracleDao" class="spring.dao.impl.UserDaoOracleImpl"></bean>
	<bean id="service" class="spring.service.impl.UserServiceImpl">
		<property name="userDao" ref="mysqlDao"></property>
	</bean>
</beans>

test.java

package spring.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import spring.dao.impl.UserDaoMySqlImpl;
import spring.dao.impl.UserDaoOracleImpl;
import spring.service.UserService;
import spring.service.impl.UserServiceImpl;
 
public class test {
	public static void main(String[] args) {
		UserServiceImpl userService = new UserServiceImpl();
		userService.setUserDao(new UserDaoMySqlImpl());
		userService.getUser();
		System.out.println("---------------");
		userService.setUserDao(new UserDaoOracleImpl());
		userService.getUser();
		ApplicationContext con=new ClassPathXmlApplicationContext("beans.xml");
		UserService us=(UserService)con.getBean("service");
		us.getUser();
	}
}

运行:


注意:

property标签的name属性和bean的set方法后跟的名称一样








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值