spring 4 泛型注入

最近对系统进行改造,发现在泛型实例初始化的时候,得不到想要的泛型。或者需要强制转换。

spring 4 开始支持泛型对象初始化,初始化方法如下:

注:使用配置文件的方法暂时还没有发现,下面是使用java annotation的方法:

package com.mitchz..toolkit.chain;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.asiainfo.iposs.toolkit.chain.spring.TestMessageContext;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * @author zhangya 
 * @version 1.0
 * @since 2014年5月25日
 * @category com.mitchz.toolkit.chain
 */
@Configuration
public class TestConfiguration
{

	@Autowired
	@Qualifier("getCustomerInfo")
	HandlerCommand<String, Object, TestMessageContext> getCustomerInfo;
	@Autowired
	@Qualifier("testDriveVehicle")
	HandlerCommand<String, Object, TestMessageContext> testDriveVehicle;
	@Autowired
	@Qualifier("negotiateSale")
	HandlerCommand<String, Object, TestMessageContext> negotiateSale;
	@Autowired
	@Qualifier("arrangeFinancing")
	HandlerCommand<String, Object, TestMessageContext> arrangeFinancing;
	@Autowired
	@Qualifier("closeSale")
	HandlerCommand<String, Object, TestMessageContext> closeSale;
	@Autowired
	@Qualifier("chain1")
	HandlerChain<String, Object, TestMessageContext> chain1;
	@Autowired
	@Qualifier("chain2")
	HandlerChain<String, Object, TestMessageContext> chain2;

	@Bean(name = "chain1")
	public HandlerChain<String, Object, TestMessageContext> createChain1()
	{
		List<HandlerCommand<String, Object, TestMessageContext>> commands = Lists
				.newArrayList();
		commands.add(getCustomerInfo);
		commands.add(testDriveVehicle);
		commands.add(negotiateSale);
		commands.add(arrangeFinancing);
		commands.add(closeSale);
		return new HandlerChain<String, Object, TestMessageContext>(commands);
	}

	@Bean(name = "chain2")
	public HandlerChain<String, Object, TestMessageContext> createChain2()
	{
		List<HandlerCommand<String, Object, TestMessageContext>> commands = Lists
				.newArrayList();
		commands.add(getCustomerInfo);
		commands.add(arrangeFinancing);
		commands.add(closeSale);
		return new HandlerChain<String, Object, TestMessageContext>(commands);
	}

	@Bean(name = "catalog")
	public HandlerCatalog<String, Object, TestMessageContext> createCatalog()
	{
		Map<String, HandlerChain<String, Object, TestMessageContext>> commands = Maps
				.newHashMap();
		commands.put("chain1", chain1);
		commands.put("chain2", chain2);
		return new HandlerCatalog<String, Object, TestMessageContext>(commands);
	}
}

 完整的例子参考:

http://spring.io/blog/2013/12/03/spring-framework-4-0-and-java-generics

posted on 2014-07-28 10:50  封起De日子  阅读(98)  评论(0编辑  收藏  举报

导航