编程语言
首页 > 编程语言> > 如何在基于Spring注释的java配置中设置活动配置文件

如何在基于Spring注释的java配置中设置活动配置文件

作者:互联网

设置有效的配置文件,如context.getEnvironment().setActiveProfiles(“DEV”);
   这可以通过使用来实现

public class SpringWebInitializer implements WebApplicationInitializer
{

    public void onStartup( final ServletContext servletContext ) throws ServletException
    {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.getEnvironment().setActiveProfiles("DEV" )

    }
}

但是在扩展AbstractAnnotationConfigDispatcherServletInitializer时.
我们如何才能设置有效的个人资料?

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { WebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

}

解决方法:

使用spring.profiles.active属性激活您的配置文件.

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { WebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
        servletContext.setInitParameter("spring.profiles.active", "DEV");
    }

}

标签:spring-4,java,spring,spring-mvc
来源: https://codeday.me/bug/20190824/1703899.html