我需要在我的构造后钩子中访问应用程序上下文。这有可能吗,如何以编程方式完成呢?
public final void systemSetup() throws Exception {
// I would like to set active profile here so I need the context.
context.getEnvironment().setActiveProfiles(APP_ENV.toLowerCase());
PrintVariables();
InitializeLimeService();
InitializeSGCSClient();
}
请指教。
我最终像这样创建了一个ApplicationContextInitializer。
package com.realitylabs.spa.tool;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
/**
* @author Pablo Karlsson
*
* ConfigurableApplicationContextInitializer sets the spring profile
* before application initialization so we can use dependency injection
* based on profile. This allows us to mock services like SGCSClientService
* In development mode.
*/
public class ConfigurableApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext context) {
String APP_ENV = System.getenv("APP_ENV");
if(APP_ENV == null) {
throw new RuntimeException("Please set APP_ENV to production or development");
}
APP_ENV = APP_ENV.toLowerCase();
if(!APP_ENV.equals("development") && !APP_ENV.equals("production")) {
throw new RuntimeException("Please set APP_ENV to production or development");
}
context.getEnvironment().setActiveProfiles(APP_ENV);
}
}
我将以下行添加到我的web.xml中
<context-param>
<param-name>contextInitializerClasses</param-name>
<param-value>com.realitylabs.spa.tool.ConfigurableApplicationContextInitializer</param-value>
</context-param>
这真的很好。谢谢您的帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句