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

Spring Map依赖注入

2015-10-26 13:55 453 查看
package com.liyang;

public interface Eat {

void  toSay() ;

}


package com.liyang;

import org.springframework.stereotype.Service;

@Service
public class HuoGuoEatImpl implements Eat{
@Override
public void toSay() {
System.out.println("老李在吃火锅!") ;
}
}


package com.liyang;

import org.springframework.stereotype.Service;

@Service
public class KfcEatImpl implements Eat{
@Override
public void toSay() {
System.out.println("老李在吃肯德基!") ;
}
}


package com.liyang;

import org.springframework.stereotype.Service;

@Service
public class DongBeiEatImpl implements Eat {

@Override
public void toSay() {
System.out.println("老李在吃东北菜!") ;
}

}


@Autowired
private Map<String, BaseService> map
key是bean名字;value就是所有实现了BaseService的Bean


package com.liyang;

import java.util.Map;

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

@Service
public class EatFactory {

@Autowired
private  Map<String , Eat> eat ;

private  final  String suffix = "EatImpl"  ;

public enum Eater{
HUOGUO("huoGuo") , KFC("kfc") , DONGBEI("dongBei") ;

private  final  String prefix ;

private Eater(String prefix) {
this.prefix = prefix ;
}
}

public  Eat getEater(Eater eater){
return eat.get(eater.prefix + suffix) ;
}
}


package com.liyang;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

import com.liyang.EatFactory.Eater;

@Service
public class Main {

@Autowired
public  static EatFactory  factory ;

public static void main(String[] args) {

String[] configLocations = { "applicationContext-resource.xml" };
ApplicationContext context = new ClassPathXmlApplicationContext(configLocations);

factory = context.getBean("eatFactory" , EatFactory.class) ;
//注意:首字母务必小写

factory.getEater(Eater.HUOGUO).toSay() ;

factory.getEater(Eater.KFC).toSay() ;

factory.getEater(Eater.DONGBEI).toSay() ;

}

}


输出:

老李在吃火锅!

老李在吃肯德基!

老李在吃东北菜!

<?xml version="1.0" encoding="UTF-8"?>
<beans default-autowire="byName"
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 
<context:component-scan base-package="com.liyang"/>

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