Spring Profiles

4

我是一名对 Spring 平台比较新的开发者。我正在实现基于 XML 的 Spring 配置文件。

我在 web.xml 中声明了一个配置文件,如下所示:

<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>dev</param-value>
</context-param>

我希望在我的Java类中获取活动配置文件的值。

这是我的第一次尝试,但由于一些问题而无法运行。

GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
String profiles[] = ctx.getEnvironment().getActiveProfiles();
System.out.println(profiles[0]);

它显示了一个 null 值。有没有什么办法在 Java 类中激活配置文件?


1
你正在读取错误的应用程序上下文,如果它是由你的Web框架初始化的,你可能需要检索它以获取活动配置文件,否则你可以在想要引用它并从那里读取它的地方注入Environment bean。 - jmj
谢谢Jigar Joshi。你能再给我一些指导吗? - user1030128
重复帖子。访问此链接以查看有关在Spring中以编程方式获取当前活动默认环境配置文件的答案:https://dev59.com/l2ox5IYBdhLWcg3wVS8J - Kris
2个回答

0
创建一个实现ApplicationContextAware接口的类
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

  public class ApplicationContextProvider implements ApplicationContextAware {
       private static ApplicationContext applicationContext = null;

        public static ApplicationContext getApplicationContext() {
            return applicationContext;
        }
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
              / / Assign the ApplicationContext into a static variable
             this.applicationContext = applicationContext;
        }
}

将其注册为bean,放入您的Spring XML文件中,并确保您的web.xml已配置好以进行拾取

<bean id="myApplicationContextProvider" class="com.your.package.name.ApplicationContextProvider"></bean>

现在从您的Java类中使用

ApplicationContextProvider.getApplicationContext().getEnvironment().getActiveProfile()

谢谢Jigar...我已经按照你说的做了,但是每当我编译我的主方法时,它就会抛出异常:在线程“main”中java.lang.NullPointerException 在com.inflinx.blog.springprofiles.web.controller.Test.main(Test.java:10) - user1030128
String profiles[] = ApplicationContextProvider.getApplicationContext().getEnvironment().getActiveProfiles(); System.out.println(profiles.length);字符串 profiles[] = ApplicationContextProvider.getApplicationContext().getEnvironment().getActiveProfiles(); System.out.println(profiles.length); - user1030128

0

你有一个web.xml文件,这意味着你正在将它部署到Servlet容器上。Spring将ApplicationContext保存在ServletContext中。有了一个ServletContext,可以按照以下方式获取ApplicationContext...

ServletContext sc = request.getSession().getServletContext();
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(sc);

如果您想在Java应用程序(main方法)或测试中设置配置文件,请为您的配置文件设置系统属性...
java -Dspring.profiles.active="dev" org.hyness.MyClass

你的示例无法工作,因为你实例化了第二个上下文,它没有使用你的web.xml文件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接