spring实战-混合装配bean

spring 还可以使用xml和JavaConfig进行混合装配Bean

TestMain

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=ServiceConfig.class)
public class TestMain {

	@Autowired
	private Service service;
	
	@Test
	public void test(){
		System.out.println(service.getConnection().getProxyInfo().getIp());
	}
}
ServiceConfig

package com.halfworlders.web;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

/**
 * 通过@ImportResource在JavaConfig中引入XML配置
 * 还可以通过@Import导入另外一个JavaConfig配置
 */
@Configuration
@ImportResource("classpath:spring-beans.xml")
public class ServiceConfig {

	@Bean
	public Service service(Connection connection) {
		return new Service(connection);
	}
}
ProxyInfoConfig
package com.halfworlders.web;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ProxyInfoConfig {

	@Bean
	public ProxyInfo proxy() {
		return new ProxyInfo();
	}
}
spring-beans.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"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c"
	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">

	<!-- 通过这种方式无法实现在XML中引入JavaConfig,如果有大神看到本帖,请告知原因 -->
	<bean id="proxyInfoConfig" class="com.halfworlders.web.ProxyInfoConfig" />

	<bean id="proxyInfo" class="com.halfworlders.web.ProxyInfo" />

	<!-- 通过c命名空间装配构造函数参数 -->
	<bean id="connection" class="com.halfworlders.web.Connection"
		c:_-ref="proxyInfo" />

</beans>

另外 ProxyInfo,Connection,Service类的定义详见  点击打开链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值