原文 内部做了这样一件事情: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());
}
}