基于反射启动Spring容器
package com.maple.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
/**
* author: HuaZhe Ray
* <p>
* describe: TODO
* <p>
* createDate: 2018/1/2
* createTime: 16:16
*/
public class TestSpring {
public static void main(String[] args) throws Exception {
List<String> xmlPaths = new ArrayList<>();
Enumeration<URL> resources = TestSpring.class.getClassLoader().getResources("services.xml");
while (resources.hasMoreElements()) {
URL nextElement = resources.nextElement();
// not load isuwang-soa-transaction-impl
if (!nextElement.getFile().matches(".*dapeng-transaction-impl.*"))
xmlPaths.add(nextElement.toString());
}
// ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new Object[]{xmlPaths.toArray(new String[0])});
// context.start();
Class<?> appClass = TestSpring.class.getClassLoader().loadClass("org.springframework.context.support.ClassPathXmlApplicationContext");
Class<?>[] parameterTypes = new Class[]{String[].class};
//根据参数 反射构造器
Constructor<?> constructor = appClass.getConstructor(parameterTypes);
Object context = constructor.newInstance(new Object[]{xmlPaths.toArray(new String[0])});
// ApplicationContext context1 = new ClassPathXmlApplicationContext("services.xml");
// context1.getBean("testService");
Method startMethod = appClass.getMethod("start");
startMethod.invoke(context);
Method m = appClass.getMethod("getBean", String.class);
TestService service = (TestService) m.invoke(context, "testService");
service.foo();
}
}