java 如何在 spring 中初始化应用程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17472954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 02:06:11  来源:igfitidea点击:

How to Initialize the application in spring?

javaspringjspspring-mvcinitialization

提问by Human Being

Now come directly to my point,

现在直接进入我的观点,

In JSPI will do the initialization process of my application like,

JSP我将做我的应用程序的初始化过程,例如,

<%! public void jsp_init(){

      //Initialise the domain server to create protocol
      //Create the logging file
}%>

Now i am going to rebuild my previous application from Servletsto Spring 3.2.

现在我打算从重建我以前的应用程序ServletsSpring 3.2

How I can I do this with Spring 3.2?

我怎样才能做到这一点Spring 3.2

One of my colleaguesaid me to do this initialization with Constructor of the Spring Controller.

我的其中一个colleague说我要这样做initialization with Constructor of the Spring Controller

Because I have created the bean for controller classin the applicationContext.xmland I am loading the applicationContext.xmlfile withe ContextLoadListnerin web.xml.

因为我已经创建了为豆controller classapplicationContext.xml和我加载的applicationContext.xml文件枝条ContextLoadListnerweb.xml

Is this the right way of Initialization ?

这是初始化的正确方法吗?

What about ApplicationListenerin spring ?

春季的ApplicationListener怎么样 ?

Which is the best way to initialize the application in spring 3.2?

在 中初始化应用程序的最佳方法是spring 3.2什么?

Hope our stack users will give a good solution.

希望我们的堆栈用户给出一个好的解决方案。

回答by Chris Thompson

Spring will do a great deal of this for you if configured properly. If you really need to execute code (vs using something that will automatically configure itself like Log4J), I would suggest registering an InitializingBeanand overriding afterPropertiesSet. You then would add this bean definition to the applicationContext.xml file:

如果配置正确,Spring 将为您做很多事情。如果你真的需要执行代码(而不是使用像 Log4J 这样会自动配置自己的东西),我建议注册一个InitializingBean并覆盖afterPropertiesSet. 然后,您可以将此 bean 定义添加到 applicationContext.xml 文件中:

<bean id="initializer" class="com.myproject.MyInitializer" />

As a result, Spring will invoke the MyInitializer.afterPropertiesSet()method when the application has been fully initialized. You alternatively could use the @PostConstructannotation on a bean that has been registered with the application context, but there's no guarantee the rest of the application will be initialized when that method gets invoked. If you want it to run when everything has been set up, the Initializing Bean method is the way to go. I've used this strategy to start a server socket, etc that needed to run independently of the web request life cycle.

因此,MyInitializer.afterPropertiesSet()当应用程序完全初始化时,Spring 将调用该方法。或者,您可以@PostConstruct在已向应用程序上下文注册的 bean 上使用注释,但不能保证在调用该方法时会初始化应用程序的其余部分。如果您希望它在一切都设置好后运行,Initializing Bean 方法就是您要走的路。我已经使用这种策略来启动需要独立于 Web 请求生命周期运行的服务器套接字等。

回答by Elbek

Why would u initialize spring application by yourself? Spring will do automatically for you: This is how you tell your server to initialize spring:

为什么要自己初始化 spring 应用程序?Spring 会自动为你做:这就是你告诉你的服务器初始化 spring 的方式:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/app.xml</param-value>
  </context-param>

  <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
  </listener>

This will happen during deploymentand all beans are defined there will be initialized(depending on laziness). If you really want to do something once bean is initialized, before usage then use InitializingBeanExample would be

这将在部署期间发生,并且所有 bean 被定义将被初始化(取决于懒惰)。如果你真的想在 bean 初始化后做一些事情,那么在使用之前使用InitializingBeanExample 将是

MyBean implements InitializingBean{
   afterPropertiesSet() {

      //do here
   }

}

回答by Risav Karna

ContextLoaderListeneris sort of bootstrapper to start up Spring's WebApplicationContextwhile ApplicationListeneris more at the java application level itself rather than at the web application context.

ContextLoaderListener是一种启动 Spring 的引导程序,WebApplicationContextApplicationListener更多的是在 Java 应用程序级别本身而不是在 Web 应用程序上下文中。

ContextLoaderListeneris a great and standard tool for the contextualization of your app if it has multiple DispatcherServlets or some servlets/servlet filters mapped to different services. Basically, it is handy to have listeners for different servlets of such apps so that you can have fine-grained contextualization.

ContextLoaderListener如果您的应用程序有多个DispatcherServlets 或一些 servlet/servlet 过滤器映射到不同的服务,那么它是一个很好的标准工具,用于将您的应用程序上下文化。基本上,为此类应用程序的不同 servlet 设置侦听器是很方便的,这样您就可以进行细粒度的上下文化。

I do not know the nature of the application you are building but I assume that you are trying something basic for now. If this is the case, and even in cases where you have a more complex setup, it is better to load on startup a controller that takes care of your main initialization routines including your contextualization. You can use the controller bean you have with something like this in your web.xml:

我不知道您正在构建的应用程序的性质,但我假设您现在正在尝试一些基本的东西。如果是这种情况,即使您有更复杂的设置,最好在启动时加载一个控制器来处理您的主要初始化例程,包括您的上下文。你可以在你的 web.xml 中使用你拥有的控制器 bean:

<servlet>
    <servlet-name>your-servlet</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

This servelt can also be mapped and invoked whenever you read a certain url pattern E.g.

每当您阅读某个 url 模式时,也可以映射和调用此服务,例如

@RequestMapping("/welcome")         
    public ModelAndView helloWorld() 

And in the web deployment descriptor, this bit is just like you map your servlets to other Spring services like Spring Security:

在 Web 部署描述符中,这有点就像您将 servlet 映射到其他 Spring 服务(如 Spring Security):

<servlet-mapping>
    <servlet-name>crunchify</servlet-name>
    <url-pattern>*.html</url-pattern>
</servlet-mapping>

So you don't really need to use the constructor of a controller and neither do you always need to use ContextLoaderListeneror other listeners for simple initialization tasks. Nevertheless, it is handy to learn their use cases as you will need it when scaling your app.

所以你真的不需要使用控制器的构造函数,你也不需要总是使用ContextLoaderListener或 其他侦听器来完成简单的初始化任务。尽管如此,了解它们的用例还是很方便的,因为在扩展应用程序时您将需要它。

Read more about dispatcher servlet here:

在此处阅读有关调度程序 servlet 的更多信息:

http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/web/servlet/DispatcherServlet.html

http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/web/servlet/DispatcherServlet.html

回答by david99world

You could do this by having a bean with @PostConstructand injecting in in your servlet-config in spring. Take a look at the code hereand one of the lines at the bottom.

您可以通过@PostConstruct在 spring中使用 bean并在您的 servlet-config 中注入来做到这一点。看看这里的代码和底部的一行。

<beans:bean id="PlayerImportDaoImpl"
        class="com.footieview.app.importer.dao.PlayerImportDaoImpl" />

This will inject this bean at startup a method on this bean has the annotation @PostConstruct- this means at startup this method gets called.

这将在启动时注入这个 bean,这个 bean 上的一个方法有注释@PostConstruct——这意味着在启动时这个方法被调用。

回答by Ayub Malik

Create a Spring 3 MVC application and you do not need to do this!

创建一个 Spring 3 MVC 应用程序,您不需要这样做!

Spring MVC supports JSPs and you can do all the configuration via Annotations

Spring MVC 支持 JSP,您可以通过 Annotations 完成所有配置

See http://fruzenshtein.com/spring-mvc-creation-of-simple-controller-with-java-based-config/for an example.

有关示例,请参见http://fruzenshtein.com/spring-mvc-creation-of-simple-controller-with-java-based-config/