利用Spring Profile支持多环境

利用Spring Profile使系统支持多环境的切换

application.xml配置文件

application-share.xml配置文件


spring-test例子

import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.alibaba.fastjson.JSON; import cn.chutong.vwdata.service.IDataTransformService; import cn.chutong.vwdata.service.IUserDataService; /** * @ClassName: AppTest * @Description: TODO * @author telinx * @date 2017年3月21日 上午11:03:26 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"file:src/main/resources/application.xml"}) @ActiveProfiles("development") public class AppTest{ private static Logger logger = Logger.getLogger(AppTest.class); private String[] idCardNos = {}; @Autowired IUserDataService userDataService; @Test public void testUser() throws Exception{ String result = null; List resultList = new ArrayList<>(); for(String idCardNo : idCardNos){ /*...*/ } logger.info(JSON.toJSONString(resultList)); } }

AppStart Main方法启动

import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.chutong.vwdata.service.IUserDataService; public class App { private ApplicationContext applicationContext; public static void main(String[] args) throws Exception { /*GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); ctx.getEnvironment().setActiveProfiles("development"); ctx.load( new String[]{"application.xml"}); ctx.refresh(); */ ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(); ctx.getEnvironment().setActiveProfiles("development"); ctx.setConfigLocations( new String[]{"application.xml"}); ctx.refresh(); IUserDataService userDataService = (IUserDataService) ctx.getBean("userDataService"); String result = userDataService.getUserData("*****************01"); System.out.println("vw_data------------>" + result); } }

你可能感兴趣的:(Spring)