您的位置:首页 > 编程语言 > Java开发

Spring @Autowired 注解常用的依赖性接口及数组、Map

2016-03-31 21:37 513 查看
@Autowired

Private ApplicationContext context

这段代码就可以获得IOC容器的上下文信息,类似的依赖性接口还有ResourseLoader,BeanFactory

关于数组与Map,我们用例子说明

第一步:写出核心xml、一个接口类BeanInterface、2个实现类BeanImpOne和BeanimpTwo、一个中间类、测试类

核心xml:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns:context="http://www.springframework.org/schema/context"

    xsi:schemaLocation="http://www.springframework.org/schema/beans

        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd" >

       

        <context:component-scan base-package="com.imooc.beanannotation"></context:component-scan>

       

 </beans>

接口类BeanInterface:

package com.imooc.beanannotation;

public interface BeanInterface {

}

2个实现类:

package com.imooc.beanannotation;

import org.springframework.stereotype.Component;

@Component

public class BeanImpOne implements BeanInterface {

}

package com.imooc.beanannotation;

import org.springframework.stereotype.Component;

@Component

public class BeanimpTwo implements BeanInterface {

}

这里用@Component是为了让Spring框架发现这2个类

中间类:

package com.imooc.beanannotation;

import java.util.List;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

@Component

public class beanInvoker {

    @Autowired

 private List<BeanInterface> list;

    @Autowired

    private Map<String, BeanInterface> map;

    public void say()

    {

     if(null!=list)

     {

      for(BeanInterface bean:list)

      {

       System.out.println(bean.getClass().getName());

       

      }

     }

     if(null!=map&& 0!=map.size())

     {

      for(Map.Entry<String, BeanInterface> entry :map.entrySet())

      {

       System.out.println(entry.getKey()+entry.getValue().getClass().getName());

      }

     }

    }

}

这是重点要讲的,我们在    @Autowired注解的list与map',作用就是告诉Spring找出BeanInterface所有的list和map(这里的Spring就是实例bean的id)

测试类

package com.imooc.beanannotation;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestInjection {

    public static void main(String[] args) {

  ApplicationContext ctx=new ClassPathXmlApplicationContext("spring-beanannotation.xml");

//  InjectionService service=(InjectionService) ctx.getBean("injectionServiceimpl");

//  service.save("this is a autowired");

  beanInvoker BI=(beanInvoker) ctx.getBean("beanInvoker");

  BI.say();

 }

}

最后,补充一下@Order(value) 的作用,value越小,越先执行

要注意@order只针对数组,不能用于Map

  看到这里,大家可能会有疑问,如果我不想输出所有类怎么办,Spring给我们提供了Qualifier,它可以缩小范围。

Qualifier的参数是bean的id,在xml中也可以配置Qualifier

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: