点击(此处)折叠或打开
-
public interface Person {
-
void sayHello();
-
}
-
-
-
public class Chinese implements Person {
-
public void sayHello() {
-
System.out.println("您好 !");
-
}
-
}
-
-
-
public class American implements Person {
-
-
public void sayHello() {
-
System.out.println("How do you do .");
-
}
-
-
}
-
-
-
-
//传统类里此类new Chinese/American
-
public class User {
-
Person p;
-
public Person getP() {
-
return p;
-
}
-
//使用setter注入
-
public void setP(Person p) {
-
this.p = p;
-
}
-
-
-
//调用person子类重写的sayHello方法,这里的p并没有实例化
-
public void function(){
-
p.sayHello();
-
}
-
-
}
-
-
-
//外部容器
-
-
public class Container{
-
-
public static User getBean(){
-
-
Person p=new Chinese();
-
-
User user = new User();
-
-
//由容器‘注入’实例
-
-
user.setP(p);
-
-
return user;
-
-
}
-
-
}
-
-
-
public class Test{
-
-
public static void main(String[] args){
-
-
User user = Container.getBean();
-
-
user.function();
-
-
}
-
- }
依赖注入的三种方式:
http://yejiansuo.iteye.com/blog/789895