srping相关配置文件:src/applicationContext.xml
package hello; public interface SpeakService { public void say(); } package hello; public class SayHello implements SpeakService { @Override public void say() { System.out.println("hello,my friend !!!!"); } } package hello; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; //import org.springframework.context.support.FileSystemXmlApplicationContext; public class testPerson { public static void main(String[] args) { //ApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext.xml"); ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); Person person = (Person) ctx.getBean("PersonBean"); person.say(); } }注入方法 1 接口注入
package hello; public class Person { private SpeakService speakService; public void say(){ try { Object obj = Class.forName("hello.SayGoodbye").newInstance(); speakService=(SpeakService)obj; speakService.say(); } catch (InstantiationException | IllegalAccessException| ClassNotFoundException e) { e.printStackTrace(); } } }在applicationContext.xml配置 <bean id="PersonBean" class="hello.Person"></bean>运行testPerson类,在控制台中可以看到testPerson类中注入了SpeakService,并调用了其say方法注入方法 2 构造方法注入
package hello; public class Person { private SpeakService speakService; public Person(SpeakService speakService) { this.speakService = speakService; } public void say(){ /*try { Object obj = Class.forName("hello.SayHello").newInstance(); speakService=(SpeakService)obj; } catch (InstantiationException | IllegalAccessException| ClassNotFoundException e) { e.printStackTrace(); }*/ speakService.say(); } }在applicationContext.xml配置 <bean id="sayHello" class="hello.SayHello"/> <!--构造方法注入 --> <bean id="PersonBean" class="hello.Person"> <constructor-arg index="0" ref="sayGoodbye"></constructor-arg> </bean> 运行testPerson依然可以看到后台打印了hello,my friend !!!! 注入方法 3 setter注入 package hello; public class Person { private SpeakService speakService; public Person(SpeakService speakService) { this.speakService = speakService; } public void say(){ /*try { Object obj = Class.forName("hello.SayHello").newInstance(); speakService=(SpeakService)obj; } catch (InstantiationException | IllegalAccessException| ClassNotFoundException e) { e.printStackTrace(); }*/ speakService.say(); } public void setSpeakService(SpeakService speakService) { this.speakService = speakService; } } 在applicationContext.xml配置 <bean id="sayHello" class="hello.SayHello"/> <!-- setter注入 --> <bean id="PersonBean" class="hello.Person"> <property name="speakService" ref="sayHello"></property> </bean> 运行testPerson依然可以看到后台打印了 hello,my friend !!!!总结:通过以上注入方法比较可以看出 接口注入必须与实现接口相关联,具有侵入性,耦合度高,一般使用 而构造器注入在构造期间实例了对象,因此如果一个需要注入多个对象,且这些对象具有有先后关系,构造器注入将是一个很好的解决办法 setter注入相对构造器注入看过去更加简洁舒服,因此如果注入的类不是很多且没有先后依赖关系,setter也是一个不错的选择。
项目测试源码下载