http://blog.163.com/taodengwen@126/blog/static/87199341201191383429693/
-
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
阅读(1571) | 评论(0) | 转发(0) |