1. 什么是IOC的功能?
* IoC -- Inverse of Control,控制反转,将对象的创建权反转给Spring!!
* 使用IOC可以解决的程序耦合性高的问题!!
2. 代码示例
1 UserService: 2 public interface UserService { 3 public void sayHello(); 4 } 5 6 UserServiceImpl: 7 public class UserServiceImpl implements UserService { 8 9 @Override 10 public void sayHello() { 11 System.out.println("Hello Spring"); 12 } 13 14 } 15 16 Demo: 17 public class Demo { 18 19 /** 20 * Manual object creation 21 */ 22 @Test 23 public void run() { 24 UserService us = new UserServiceImpl(); 25 us.sayHello(); 26 } 27 28 /** 29 * IOC: Give the right to create objects to the Spring container 30 */ 31 @SuppressWarnings("resource" ) 32 @Test 33 public void run2() { 34 // Create a factory and load the appliCationContext.xml configuration file 35 ApplicationContext context = new ClassPathXmlApplicationContext("/config/spring-mvc.xml"); 36 37 // 获取对象 38 UserService us = (UserService) context.getBean("userService"); 39 40 us.sayHello(); 41 } 42 }