如何在首次运行时配置您的应用程序?

时间:2017-09-08 04:18:45

标签: java spring-mvc web-applications login

我在这里很困惑,我不知道我是否在问一个愚蠢的问题。场景是这样的, 我在开发环境中创建了一个应用程序,我想在生产中部署应用程序,因此我清空了数据库中的所有表,包括用户。我没有可以添加用户的注册页面。注册由管理员完成。当我截断用户表时,我也没有管理员。但是在第一次运行时,我需要创建一个可以添加用户并配置应用程序的超级管理员。

  1. 我们可以这样做,当应用程序第一次运行时,我们可以检查表是否为空,是否写了一个逻辑来创建用户并使用用户详细信息登录。
  2. 此问题还有其他逻辑吗?如果我以错误的方式做这件事,请纠正我。我使用Spring MVC和Hibernate进行开发。

2 个答案:

答案 0 :(得分:2)

访问具有应用程序引导程序的模块,然后在数据库表上手动注册超级用户(admin)。

请记住,如果控件已经存在,或者您将非常快速地填充表格,则必须设置控件;)如果需要,您只需调用一个函数来验证表是否为空:如果是,只需询问用户名和密码(如果您以这种方式注册用户),只需将第一个用户注册为超级用户。

答案 1 :(得分:1)

是的,您可以通过实施WebApplication初始化程序来实现此目的。

将以下类添加到项目中

public class SpringDispatcherConfig implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext container) {
        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(ApplicationConfig.class);

        // Manage the lifecycle of the root application context
        container.addListener(new ContextLoaderListener(rootContext));

        // Create the dispatcher servlet's Spring application context
        AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
        dispatcherContext.register(ApplicationConfig.class);

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher = container.addServlet("SpringDispatcher", new DispatcherServlet(dispatcherContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/*");
    }

}

然后你需要ApplicationEventListnerClass并在应用程序启动时触发带注释的方法,你可以在其中实现创建用户的功能

@Component
public class ApplicationStartListener {


    @EventListener
    public void handleContextRefresh(ContextRefreshedEvent event) {

        String id = event.getApplicationContext().getId();
        if (id.startsWith("org.springframework.web.context.WebApplicationContext:") && !id.endsWith("SpringDispatcher")) {
            //implement your on startup functionality here

        }
    }
}