gpt4 book ai didi

Spring 单独的 applicationContext 的目的

转载 作者:行者123 更新时间:2023-11-28 20:43:41 25 4
gpt4 key购买 nike

我有以下类来实例化正确的管理器,因此我可以将一个用于暂存、发布,另一个用于测试:

public class DAOFactory {
private static final Logger LOG = LoggerFactory.getLogger(DAOFactory.class);

@Autowired
private static ApplicationContext applicationContext;
private final static String dataSourceName = "remoteStagingDataSource";

// TODO : Change variable dataSourceName to the correct DataSource if you deploy on staging/release web server
// -- remoteStagingDataSource -- for deploying on local tomcat server
// -- stagingDataSource -- for deploying on staging server + uncomment the correct bean in src/main/resources/applicationContext.xml
// -- releaseDataSource -- for deploying on release server + uncomment the correct bean in src/main/resources/applicationContext.xml
public static DAOManager createMySQLDAOManager() {
LOG.info("Setting up datasource to " + dataSourceName);
DataSource dataSource = setupDataSource(dataSourceName);
return new DAOManager(dataSource);
}

public static DAOManager createHSQLDBDAOManager() {
LOG.info("Setting up datasource to in-memory HSQLDB");
DataSource dataSource = setupDataSource("hsqldbDataSource");
return new DAOManager(dataSource);
}

private static DataSource setupDataSource(final String dataSourceName) {
applicationContext = new ClassPathXmlApplicationContext("classpath:/applicationContext.xml");
return (DataSource)applicationContext.getBean(dataSourceName);
}
}

现在我想分离 applicationContext 用于测试目的(DBUnit 测试我的 DAO)

所以两个xml文件:

  • applicationContext.xml
  • applicationContext-test.xml

知道如何实现吗?

最佳答案

Spring 提供 Profiles这允许在运行时根据应用程序所在的环境有条件地选择 bean 实例。

简而言之,您使用 beans 标签包装环境相关的 beans,该标签将 profile 定义为属性:

<beans profile="DEV">
<bean id="someBean" class="x.y.ClassA"/>
<beans>
<beans profile="QA">
<bean id="someBean" class="x.y.ClassB"/>
<beans>

然后设置系统属性以确定要运行的环境:

-Dspring.profiles.active="QA"

关于Spring 单独的 applicationContext 的目的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22435654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com