根据bean的id 读取spring 文件中的bean
·servlet中
private static ApplicationContext ctx = null;
@Override
public void init(ServletConfig config) throws ServletException {
if(ctx == null){
ctx = WebApplicationContextUtils
.getRequiredWebApplicationContext(config.getServletContext());
}
}
·普通java类中
private static ApplicationContext ctx = null;
public 方法()
{
if (ctx == null) {
if (ServletActionContext.getServletContext() != null) {
ctx = WebApplicationContextUtils
.getWebApplicationContext(ServletActionContext
.getServletContext());
} else {
ctx = SpringBean.getCtx();
}
}
}
//SpringBean 类
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.opensymphony.xwork2.util.ClassLoaderUtil;
public class SpringBean {
private static ApplicationContext ctx = null;
@SuppressWarnings("unchecked")
public static ApplicationContext getCtx() {
if (ctx == null) {
URL fileUrl = ClassLoaderUtil.getResource("", SpringBean.class);
File file = new File(fileUrl.getPath());
List s = new ArrayList();
for (int i = 0; i < file.list().length; i++) {
if (file.list()[i].startsWith("spring-")
&& file.list()[i].endsWith(".xml")) {
s.add(file.list()[i]);
}
}
String[] spring = new String[s.size()];
int i = 0;
for (Iterator iter = s.iterator(); iter.hasNext();) {
spring[i] = iter.next() + "";
System.out.println(spring[i]);
i++;
}
ctx = new ClassPathXmlApplicationContext(spring);
}
return ctx;
}
}
具体的用法
具体要生成那个接口的对象的话 (转型)ctx.getBean("xxx");返回的是object型 xxx表示 spring 配置文件中的 bean 的id
转载于:https://www.cnblogs.com/li-yg/archive/2012/10/20/2732182.html