Spring中的IOC(一)

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      * 手动创建对象
21      */
22     @Test
23     public void run() {
24         UserService us = new UserServiceImpl();
25         us.sayHello();
26     }
27     
28     /**
29      * IOC:将创建对象权交给Spring容器
30      */
31     @SuppressWarnings("resource")
32     @Test
33     public void run2() {
34         // 创建工厂,加载appliCationContext.xml配置文件
35         ApplicationContext context = new ClassPathXmlApplicationContext("/config/spring-mvc.xml");
36         
37         // 获取对象
38         UserService us = (UserService) context.getBean("userService");
39         
40         us.sayHello();
41     }
42 }
View Code


猜你喜欢

转载自www.cnblogs.com/liyue-sqsf/p/9005925.html