1.新建类,并实现 org.springframework.context.ApplicationContextAware 接口.
package com.abc.framework.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* 在容器启动后,也可以通过 getBean(String name) 得到对象
* @author Administrator
* <!-- 需要在spring.xml 里写 -->
* <bean class="com.abc.framework.util.ApplicationContextHandle" lazy-init="false"/>
*/
public class ApplicationContextHandle implements ApplicationContextAware{
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextHandle.applicationContext = applicationContext;
}
/**
* 获取对象
* 这里重写了bean方法,起主要作用
* @param name
* @return Object 一个以所给名字注册的bean的实例
* @throws BeansException
*/
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
}
2.在spring.xml内添加:
<bean class="com.abc.framework.util.ApplicationContextHandle" lazy-init="false"/>3.应用:
private static final AttachmentService as = (AttachmentService)ApplicationContextHandle.getBean("attachmentService");

本文详细介绍了如何在Spring框架中实现ApplicationContextAware接口,并通过自定义类ApplicationContextHandle来获取和使用Spring容器中的对象,包括在Spring.xml配置文件中添加bean实例及实际应用示例。
3103

被折叠的 条评论
为什么被折叠?



