使用spring进行属性注入的实例解析(spring面向切面和控制反转)。
使用spring条件:对私有属性进行对象注入的时候,注意一定要有该属性对应的SETTER方法。
子类:
public class sub {
public int add(){
int a=2;
int b=3;
return a+b;
}
}
父类:
public class sup {
private sub b;
public int supAdd(){
// b=new sub(); //代码1 注释处
return b.add();
}
}
测试类:
public class test {
public static void main(String[] args) {
sub b=new sub();
int count1=b.add();
System.out.println(count1);
sup s=new sup();
int count2=s.supAdd();
System.out.println(count2);
}
}
使用spring的好处,简单的说明就是在代码1 处不用对私有属性进行实例化,而通过注入的方式完成这个实现,也是spring控制反转和面向切面的核心理念。