160922、配置:spring通过profile或@profile配置不同的环境(测试、开发、生产)
一、配置环境 applicationContext.xml中添加下边的内容(develop:开发环境,production:生产环境,test:测试环境) 注意:profile的定义一定要在文档的最下边 <beans profile="develop"> <context:property-placeholder location="classpath*:jdbc-develop.properties"/> </beans> <beans profile="production"> <context:property-placeholder location="classpath*:jdbc-production.properties"/> </beans> <beans profile="test"> <context:property-placeholder location="classpath*:jdbc-test.properties"/> </beans> 二、切换环境 在web.xml中添加一个context-param来切换当前环境: <context-param> <param-name>spring.profiles.active</param-name> <param-value>develop</param-value> </context-param> java代码可以这样做 import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.hmkcode.vo.Person; public class App { public static void main( String[] args ) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.getEnvironment().setActiveProfiles("develop"); //or production ctx.scan("com.hmkcode.spring"); // register all @Configuration classes //ctx.register(SpringConfigDev.class); ctx.refresh(); Person person = (Person)ctx.getBean("person"); System.out.println("Person: "+person); } } 三、java代码 package com.myapp; import javax.activation.DataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.jndi.JndiObjectFactoryBean; @Configuration public class DataSourceConfig { @Bean(destroyMethod="shutdown") @Profile("develop") public DataSource embeddedDataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) .addScript("classpath:schema.sql") .addScript("classpath:test-data.sql") .build(); } @Bean @Profile("production") public DataSource jndiDataSource() { JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean(); jndiObjectFactoryBean.setJndiName("jdbc/myDS"); jndiObjectFactoryBean.setResourceRef(true); jndiObjectFactoryBean.setProxyInterface(javax.sql.DataSource.class); return (DataSource) jndiObjectFactoryBean.getObject(); } }