Spring:使用默认装配方式Spring降低耦合度

我们创建一个接口:ISomeInterface,里面有个方法,void doSome();

创建一个Student类,继承这个接口并实现该方法:

public void doSome() {

// TODO Auto-generated method stub

System.out.println("执行dosomg方法!!!");

我们之前的测试类是这样的:

Student student=new Student();

studetn.doSome();

这样测试类和Student类完全耦合在一起,我们今天使用Spring就是要降低耦合度。


第一步:导入Jar包:

com.springsource.org.apache.commons.logging-1.1.1.jar

spring-beans-4.3.6.RELEASE.jar

spring-context-4.3.6.RELEASE.jar

spring-core-4.3.6.RELEASE.jar

spring-expression-4.3.6.RELEASE.jar

第二步:在src下创建xml文件,取名为:applicationContext.xml

Spring:使用默认装配方式Spring降低耦合度

applicationContext.xml

<bean>的底层是通过反射机制创建对象的:

Object student=class.forName("com.abc.Beans.Student").newInstance();

会自动调用无参构造器,倘若Student里的无参构造器变成这样就会出错:

Spring:使用默认装配方式Spring降低耦合度

第三步:编写测试类:

Spring:使用默认装配方式Spring降低耦合度

测试类