发布于 2017-08-27 07:58:20 | 201 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的精品教程,程序狗速度看过来!

Spring Framework 开源j2ee框架

Spring是什么呢?首先它是一个开源的项目,而且目前非常活跃;它是一个基于IOC和AOP的构架多层j2ee系统的框架,但它不强迫你必须在每一层 中必须使用Spring,因为它模块化的很好,允许你根据自己的需要选择使用它的某一个模块;它实现了很优雅的MVC,对不同的数据访问技术提供了统一的接口,采用IOC使得可以很容易的实现bean的装配,提供了简洁的AOP并据此实现Transcation Managment,等等


这篇文章主要介绍了详解 Spring注解的(List&Map)特殊注入功能的相关资料,需要的朋友可以参考下

详解 Spring注解的(List&Map)特殊注入功能

最近接手一个新项目,已经没有原开发人员维护了。项目框架是基于spring boot进行开发。其中有两处Spring的注解花费了大量的时间才弄明白到底是怎么用的,这也涉及到spring注解的一个特殊的注入功能。

首先,看到代码中有直接注入一个List和一个Map的。示例代码如下:


@Autowired
private List<DemoService> demoServices;

@Autowired
private Map<String,DemoService> demoServiceMap;

以上是两处代码示例化之后的demo。当时看到这里之后有些懵,全局搜索之后并没有发现定义一个List和Map的对象。然而debug运行之后却发现它们的确都有值。这个事情就有些神奇了。在网上搜索也收获甚微。

最后在调试List的时候突然灵感一闪,如果只有一个对象那么List里面的值不就只有一个吗。于是开始测试验证,结果发现的确如此。当实例化一个DemoService之后,另外一个类采用泛型注入List,Spring竟然成功的将实例化的对象放入List之中。思路打开之后,针对Map的就更好说了。Spring会将service的名字作为key,对象作为value封装进入Map。

具体事例代码如下

DemoService代码:


package com.secbro.learn.service;

import org.springframework.stereotype.Service;

/**
 * Created by zhuzs on 2017/5/8.
 */
@Service
public class DemoService {

  public void test(){
    System.out.println("我被调用了");
  }

}

DemoController代码:


package com.secbro.learn.controller;

import com.secbro.learn.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * Created by zhuzs on 2017/5/8.
 */
@Controller
@RequestMapping(value = "/demo")
public class DemoController {

  @Autowired
  private List<DemoService> demoServices;

  @Autowired
  private Map<String,DemoService> demoServiceMap;

  @ResponseBody
  @RequestMapping(value = "/test")
  public String test(){
    for(Map.Entry<String,DemoService> entry : demoServiceMap.entrySet()){
      entry.getValue().test();
    }
    System.out.println("===============分割线=============");
    for(DemoService demoService : demoServices){
      demoService.test();
    }

    return "success";
  }
}

运行之后,访问http://localhost:8080/demo/test 执行结果如下:


我被调用了
===============分割线=============
我被调用了

原来,在不知不觉中Spring已经帮我们做了很多事情,只是我们不知道而已。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务