package com.sand.spring.util; import org.junit.After; import org.junit.Before; import org.junit.runner.RunWith; import org.junit.runners.BlockJUnit4ClassRunner; import org.springframework.beans.BeansException; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.util.StringUtils; /** * 功能说明:spring容器启动类 * 开发人员:@author liusha * 开发日期:2020/3/30 15:34 * 功能描述:用于加载spring的配置文件 */ @RunWith(BlockJUnit4ClassRunner.class) public class SpringBootStrap { private String springXmlPath; private ClassPathXmlApplicationContext context; public SpringBootStrap() { } public SpringBootStrap(String springXmlPath) { this.springXmlPath = springXmlPath; } @Before public void before() { if (StringUtils.isEmpty(springXmlPath)) { springXmlPath = "classpath*:application-context.xml"; } try { context = new ClassPathXmlApplicationContext(springXmlPath.split("[,\s]+")); context.start(); System.out.println("容器启动完成!"); } catch (BeansException e) { System.out.println("容器启动失败!"); e.printStackTrace(); } } @After public void after() { System.out.println("关闭容器!"); context.destroy(); } protected <T extends Object> T getBean(String name) { return (T) context.getBean(name); } protected <T extends Object> T getBean(Class<?> clz) { return (T) context.getBean(clz); } }