依赖注入

Spring框架注入与Bean实例化
本文详细介绍了如何使用Spring框架进行Bean实例化,并通过配置文件实现对象的依赖注入,展示了如何通过构造函数参数和属性注入来管理对象之间的依赖关系。

原文  内部做了这样一件事情:Foo f=new Foo("Cleopatra");

package basicinjection;
/**
 * 
 * @author Apurav
 *
 */
public class Foo {
	private String name;

	public Foo() {
	}

	public Foo(String name) {
		this.name = name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

}


package basicinjection;
/**
 * 
 * @author Apurav
 *
 */
public class Bar {
	private String name;
	private int age;
	private Foo foo;
	public Bar() {}
	public Bar(String name,int age) {
		this.name = name;
		this.age = age;
	}
	public void setFoo(Foo foo) {
		this.foo = foo;
	}
	
	public void processFooName(){
		System.out.println("Name in Injected Foo is: "+foo.getName());
	}
	
	@Override
	public String toString() {
		return "Bar has name = "+this.name+" and age = "+this.age;
	}
	
}


<?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-3.0.xsd">

	<bean id="foo" class="basicinjection.Foo" scope="prototype">
		<constructor-arg index="0" value="Cleopatra"></constructor-arg>
	</bean>
	<bean id="bar" class="basicinjection.Bar">
		<constructor-arg type="int" value="26" />
		<constructor-arg type="java.lang.String" value="Arthur" />
		<property name="foo" ref="foo"></property>
	</bean>

</beans>

package basicinjection;

import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * 
 * @author Apurav
 *
 */
public class TestFooBar {

	public static void main(String[] args) throws InterruptedException {
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
				"basicinjection/springbasic.xml");
		Bar bar = applicationContext.getBean("bar", Bar.class);
		bar.processFooName();
		System.out.println(bar.toString());
		/*
		 * if a single definition of a class type exists, then u can get the
		 * instance by this way also. No need to specify Id
		 */
		Foo foo = applicationContext.getBean(Foo.class);
		System.out.println(foo.getName());
	}

}


含库源代码


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值