import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class SpringContextInit {
private static SpringContextInit instance;
private SpringContextInit() {
instance = this;
}
public static SpringContextInit getInstance() {
if (instance == null) {
instance = new SpringContextInit();
}
return instance;
}
public void init() {
String path = System.getProperty("user.dir");
path = path + "/resource/bean";
File file = new File(path);
if (file != null && file.isDirectory()) {
File[] files = file.listFiles();
Map<Integer, String> map = new HashMap<Integer, String>();
int i = 0;
for (File f : files) {
if (f.isFile()) {
map.put(i++, f.getName());
}
}
String[] filesName = new String[i];
if (!map.isEmpty()) {
int k = 0;
for (Integer ii : map.keySet()) {
filesName[k++] = "bean/" + map.get(ii);
}
}
new ClassPathXmlApplicationContext(filesName);
}
}
public void load() {
// 1.加载方式classpathResource
/*
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:bean/*.xml");
ManagerGlobalProps globalProperties = (ManagerGlobalProps)ctx.getBean("globalProperties", ManagerGlobalProps.class);
String zoneId = globalProperties.getZoneId();
System.out.println("zoneId = " + zoneId);*/
//String[] arr
String path = System.getProperty("user.dir");
System.out.println("path = " + path);
String absolutePath = path + "/resource/bean";
System.out.println("absolutePath = " + absolutePath);
File file = new File(absolutePath);
//2 .绝对路径
/*String[] configs = null;
if (file != null && file.isDirectory()) {
File[] files = file.listFiles();
configs = new String[files.length];
int i = 0;
for (File f : files) {
configs[i++] = f.getAbsolutePath();
System.out.println("config = " + f.getAbsolutePath());
}
}
//绝对路径
new FileSystemXmlApplicationContext(configs);*/
//3.相对路径
String[] relativePath = null;
if (file != null && file.isDirectory()) {
File[] files = file.listFiles();
relativePath = new String[files.length];
for (int i = 0; i < files.length; i++) {
relativePath[i] = "bean/"+files[i].getName();
System.out.println("relativePath = " + relativePath[i]);
}
}
//相对路径
new ClassPathXmlApplicationContext(relativePath);
//4.springtest+junit
}
public static void main(String[] args) {
SpringContextInit.getInstance().load();
}
}