精通Spring4.0企业级开发实战--IOC容器

精通Spring4.0企业级开发实战--IOC容器_第1张图片

         Spring就是这样一个第三方容器,它通过配置文件注解描述类与类之间的依赖关系,自动完成类的初始化依赖注入工作

精通Spring4.0企业级开发实战--IOC容器_第2张图片

精通Spring4.0企业级开发实战--IOC容器_第3张图片

反射:

精通Spring4.0企业级开发实战--IOC容器_第4张图片

反射示例:

car类:

package reflect;
public class Car {
    private String brand;
    private String color;
    private int maxSpeed;

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public int getMaxSpeed() {
        return maxSpeed;
    }

    public void setMaxSpeed(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }

    public Car(){

     }
     public Car(String brand,String color,int maxSpeed){
         this.brand=brand;
         this.color=color;
         this.maxSpeed=maxSpeed;
     }
     public void introduce(){
         System.out.println("brand="+brand+";color"+color+";maxSpeed"+maxSpeed);
     }}
通过反射调用car中方法,及car的构造函数等
public class ReflectTest {

    private static Method setBrand;
    private static Method setColor;
    private static Method setMaxSpeed;

    public static Car initByDefaultConst() throws Exception {
        //通过类加载器获得class对象
        Class aClass = null;
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        aClass = contextClassLoader.loadClass("reflect.Car");

       //获取类的默认构造器对象并通过它实例化car
        Constructor constructor = aClass.getDeclaredConstructor((Class[]) null);
        Car car = (Car) constructor.newInstance();

        setBrand = aClass.getMethod("setBrand", String.class);
        setBrand.invoke(car,"lsadkfjklasd");
        setColor = aClass.getMethod("setColor", String.class);
        setColor.invoke(car,"红色");
        setMaxSpeed = aClass.getMethod("setMaxSpeed", int.class);
        setMaxSpeed.invoke(car,10);

        return car;

    }
    public static void main(String[] args) {
        Car car=null;
        try {
              car =initByDefaultConst();
        } catch (Exception e) {
            e.printStackTrace();
        }
        car.introduce();
    }

}
 
  
类加载器classLoder
精通Spring4.0企业级开发实战--IOC容器_第5张图片

 
  
 
  





























































你可能感兴趣的:(精通Spring4.0企业级开发实战--IOC容器)