Spring进阶之路(3)-bean获得Spring的容器

在实际使用的时候,我们可能会希望通过当前的类的实例找到他所在的spring容器,然后从这个容器中获取到想要获取的对象,因为有的时候通过部分的注解不好实现注入某个想要获得的对象的实例,这个时候这种方式:先拿到当前对象的实例,然后获取到他所在的spring容器,然后从这个容器当中,取出想要的那个对象的实例,完成想要完成的功能即可。


为了让Bean获取到他的所在的Spring容器,可以让这个Bean去实现一个ActionContextAware接口,这个接口需要实现它的一个方法,就是:setApplicationContext(ApplicationContext context)方法。这个方法的赋值不是我们程序员为其赋值的,而是spring容器本身会为他赋值,在初始化这个bean的同时,检测到这个Bean实现了ApplicationContextAware这个接口,那么Spring容器就会直接将自身赋值给setApplicationContext这个方法。


那么下面还是一段熟悉的例子:

假设这里我不好直接注入bean的实例,但是又需要这样的一个实例。

首先是一个Message的接口:

package com.siti.spring20160228.beanapplication;

public interface MessageService {

	/**
	 * 消息打印
	 */
	public void printMessage();
}
实现

package com.siti.spring20160228.beanapplication;

public class MessagePrinter implements MessageService {

	@Override
	public void printMessage() {
		System.out.println("输出消息!");
	}

}

同样还是Person的接口:

package com.siti.spring20160228.beanapplication;

public interface Person {

	/**
	 * 人发送消息
	 */
	public void sendMessage();
}

实现Person接口以及ApplicationContextAware接口

package com.siti.spring20160228.beanapplication;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class WangYang implements Person, ApplicationContextAware{

	private MessageService service;

	public void setService(MessageService service) {
		this.service = service;
	}

	/**
	 * 实现person接口中的方法
	 */
	@Override
	public void sendMessage() {
		this.service.printMessage();
	}

	/**
	 * 实现ApplicationContextAware中的方法
	 */
	@Override
	public void setApplicationContext(ApplicationContext context)
			throws BeansException {
		this.service = context.getBean("messageService", MessageService.class);
	}

}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="messageService" class="com.siti.spring20160228.beanapplication.MessagePrinter"></bean>
	<bean id="wy" class="com.siti.spring20160228.beanapplication.WangYang"></bean>
	 
</beans>


测试类:

package com.siti.spring20160228.beanapplication;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainTest {

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext20160228.xml");
		Person wy = (Person) context.getBean("wy", Person.class);
		wy.sendMessage();
	}
}

执行结果如下:





评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值