spring IOC——注入bean实例

在spring中IOC容器占据了很核心的功能,通过IOC容器可以完全 管理java Bean ,包括创建,销毁,还可以对数据库的java Bean进行自动化的事务处理,IOC的容器是实现了BeanFctory接口的实现类,ApplicationContext是BeanFactory的子接口,BeanFactory接口提供了最基本的对象管理功能,子接口AplicationContext提供了更多的功能

BeanFactory取得Bean的创建时间:第一次使用getBean时创建指定类对象

ApplicationContext取得Bean的创建时间:自身被容器初始化时就创建全部类对象

IOC方式:

添加spring框架:新建项目右键——myeclipse——project facets——install spring facets默认next

UserOperate

package com.operate;
//声明一个接口
public interface UserOperate {

	public void user(String name);
}

UserOperateImpl

package com.operate;

public class UserOperateImpl implements UserOperate{

	@Override
	public void user(String name) {
		System.out.println("名称"+name);
	}

}

TestRun其中IOC容器是通过xml文件获得的,IOC容器里有很多由IOC容器自动创建的bean,通过getBean来取得一个指定的Bean实例,getBean的值来自xml文件中id为run的对象

package com.run;

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

import com.operate.UserOperateImpl;

public class TestRun {

	private UserOperateImpl userOperateImpl;

	public UserOperateImpl getUserOperateImpl() {
		return userOperateImpl;
	}

	public void setUserOperateImpl(UserOperateImpl userOperateImpl) {
		System.out.println(userOperateImpl);
		this.userOperateImpl = userOperateImpl;
	}

	public static void main(String[] args) {
		// 取得上下文接口
		ApplicationContext apl = new ClassPathXmlApplicationContext(
				"applicationContext.xml");
		// 从IOC容器中取出Bean
		TestRun run = (TestRun) apl.getBean("run");
		run.userOperateImpl.user("自来也");
	}
}

applicationContext

扫描二维码关注公众号,回复: 2905890 查看本文章

bean标签的功能是声明一个类,然后通过IOC窗口创建出来,id代表这个对象的变量名称,class代表要创建的是哪个类。

property子标签里,userOperateImpl是TestRun中的全局变量,ref是关联上一个bean,来对属性变量进行注入

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	<bean id="userimpl" class="com.operate.UserOperateImpl"/>
	<bean id="run" class="com.run.TestRun" >
		<property name="userOperateImpl" ref="userimpl"/>
	</bean>

</beans>

运行效果

传统方法

service

package com.service;

public class Save {

	public void save(){
		System.out.println("save....");
	}
}

 run

package com.test;

import com.service.Save;

public class RunTest {

	Save Save = new Save();
	
	public void setSave(Save save){
		Save = save;
	}
	
	public static void main(String[] args) {
		RunTest run = new RunTest();
		run.Save.save();
	}
}

猜你喜欢

转载自blog.csdn.net/Milan__Kundera/article/details/82050562