spring的依赖注入(DI)、控制反转(IOC)和面向切面(AOP)

在spring的配置文件增加

<context:component-scan base-package="com.jmu.ccjoin.service"/>
<context:annotation-config />
 1 public interface UserService {
 2 
 3     /**
 4      * 根据ID获取用户信息
 5      * 
 6      * @param id
 7      * @return
 8      */
 9     void get(Long id);
10 }
1 public interface BuyerService {
2 
3     void get();
4 }
@Service
public class BuyerServiceImpl implements BuyerService {

    @Override
    public void get() {
        System.out.println("buyer landing...");
    }

}
 1 @Service
 2 public class UserServiceImpl implements UserService {
 3 
 4     //没有UserDao类型注入到spring容器成bean
 5 //    @Autowired
 6 //    private UserDao userDao;
 7     
 8     @Autowired
 9     private BuyerService buyerService;
10 
11     public void get(Long id) {
12         buyerService.get();
13         System.out.println("userServiceImpl run sucess!!");
14     }
15 }
 1 public static void main(String[] args) {
 2 
 3         ApplicationContext app = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
 4         UserController userController = (UserController) app.getBean("userController");
 5         userController.save();
 6         
 7         System.out.println("----------------------------------");
 8         
 9         UserServiceImpl userServiceImpl = (UserServiceImpl)app.getBean("userServiceImpl");
10         userServiceImpl.get(1L);
11         
12         System.out.println("----------------------------------");
13         //userServiceImpl有注入到Spring容器,而userService并未注入到spring容器
14         UserService userService = (UserService)app.getBean("userServiceImpl");
15         userService.get(1L);
16     }

注意:userServiceImpl和userService的类型都是userService,而userService并未在spring注册成bean,所以userService类型只能取到userServiceImpl

在使用@Autowired时,首先在容器中查询对应类型的bean

    如果查询结果刚好为一个,就将该bean装配给@Autowired指定的数据

    如果查询的结果不止一个,那么@Autowired会根据名称来查找。

    如果查询的结果为空,那么会抛出异常。解决方法时,使用required=false

spring就会去自动扫描base-package对应的路径或者该路径的子包下面的java文件,如果扫描到文件中带有@Service,@Component,@Repository,@Controller等这些注解的类,则把这些类注册为bean


DI依赖注入:只需要依赖spring-context包,依赖注入的是接口的话,接口一定要有实现。
IOC控制反转:本来交给调用方new的,现在交给spring创建,并注入到调用方,控制方发生了反转。
AOP面向切面:其应用如动态代理--要执行的方法,交给spring代理执行,并在调用方法前后加入其它逻辑。

另外:

IOC能够被分解为两种子类型:依赖注入和依赖查找。

(1) 依赖查找

比如使用 JNDI 注册一个数据库连接池的示例中,代码中从注册处获得依赖关系的 JNDI 查找 (JNDI lookups):

CODE:
initContext = new InitialContext();
// 获取数据源
DataSource ds = (DataSource)initContext.lookup("java:comp/env/jdbc/mysql");

(2) 依赖注入

依赖注入的三种实现类型:接口注入、 Setter 注入和构造器注入。

猜你喜欢

转载自www.cnblogs.com/wzk-0000/p/9340803.html