三个配置文件 application.xml applicaiton-dev.xml applicaiton-pro.xml
application.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<import resource="classpath:application-dev.xml"/>
<import resource="classpath:application-pro.xml"/>
</beans>
application-dev.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans profile="dev" xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="user" name="userAlias" class="spring.User"/>
<bean id="userService" class="spring.UserService"/>
</beans>
application-pro.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans profile="pro" xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="userPro" name="userAliasPro" class="spring.User"/>
<bean id="userServicePro" class="spring.UserService"/>
</beans>
设置我们的环境:测试 开发 生产 参考资料:https://www.baeldung.com/spring-profiles
//-Dspring.profiles.active=dev System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "pro");
ClasspathXMLApplicationContext ctx = new ClasspathXMLApplicationContext("classpath:application.xml");
源码见:
// Tell the subclass to refresh the internal bean factory. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();