Spring 3.1中的默认配置文件

Mic*_*iel 99 java spring profiles

在我的应用程序中,我使用@Profile("prod")和注释bean @Profile("demo").第一个,正如你可以猜到:),用于连接到生产数据库的bean,第二个用于注释使用一些假数据库(HashMap或其他)的bean - 以加快开发速度.

我想要的是默认配置文件("prod"),如果它没有被" something-else " 覆盖,它将被使用.

完美将是我的web.xml:

<context-param>
     <param-name>spring.profiles.active</param-name>
     <param-value>prod</param-value>
</context-param>
Run Code Online (Sandbox Code Playgroud)

然后覆盖它,-Dspring.profiles.active="demo"以便我可以这样做:

mvn jetty:run -Dspring.profiles.active="demo". 
Run Code Online (Sandbox Code Playgroud)

但遗憾的是,这不起作用.任何想法我怎么能得到那个?-Dspring.profiles.active="prod"不能在我的所有环境中进行设置.

and*_*dih 110

在web.xml中将生产环境定义为默认配置文件

<context-param>
   <param-name>spring.profiles.default</param-name>
   <param-value>prod</param-value>
</context-param>
Run Code Online (Sandbox Code Playgroud)

如果要使用其他配置文件,请将其作为系统属性传递

mvn -Dspring.profiles.active="demo" jetty:run
Run Code Online (Sandbox Code Playgroud)

  • 不,他试图在web.xml中定义**active**配置文件并将其作为系统属性.在我的解决方案中,我在web.xml中配置**default**配置文件,并通过系统属性覆盖/定义*active*配置文件.如果没有明确的*active*配置文件,则将使用默认值. (3认同)

小智 67

我的经验是使用

@Profile("default")
Run Code Online (Sandbox Code Playgroud)

如果没有识别出其他配置文件,则只会将bean添加到上下文中.如果您传入不同的配置文件,例如-Dspring.profiles.active="demo",此配置文件将被忽略.

  • 接受的答案取决于web.xml(这很好),但无论你是否有web.xml,这个答案都有效,因此对每个人来说都更有用. (4认同)

bla*_*lle 5

您也可以考虑删除PROD配置文件,并使用@Profile("!demo")

  • 我想如果你有两个以上的个人资料,这不会起作用,对吧? (2认同)

mco*_*ive 5

我有同样的问题,但我使用WebApplicationInitializer以编程方式配置ServletContext(Servlet 3.0+).所以我做了以下事情:

public class WebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext sc) throws ServletException {
        // Create the 'root' Spring application context
        final AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        // Default active profiles can be overridden by the environment variable 'SPRING_PROFILES_ACTIVE'
        rootContext.getEnvironment().setDefaultProfiles("prod");
        rootContext.register(AppConfig.class);

        // Manage the lifecycle of the root application context
        sc.addListener(new ContextLoaderListener(rootContext));
    }
}
Run Code Online (Sandbox Code Playgroud)