Java Spring应用程序一次性运行技术之间的区别?
与大多数框架一样,Spring提供了不止一种方法来做一些事情。我正在考虑如何在应用程序启动时只运行一次Java方法。我发现至少有两种方法可以用Spring实现这一点 一种方法是将Java类变成Springbean。将类似以下内容添加到配置XML文件:Java Spring应用程序一次性运行技术之间的区别?,java,spring,startup,Java,Spring,Startup,与大多数框架一样,Spring提供了不止一种方法来做一些事情。我正在考虑如何在应用程序启动时只运行一次Java方法。我发现至少有两种方法可以用Spring实现这一点 一种方法是将Java类变成Springbean。将类似以下内容添加到配置XML文件: <bean name="com.mycomp.service.EngineImpl" class="com.mycomp.service.EngineImpl" /> <bean name="/Engin
<bean name="com.mycomp.service.EngineImpl"
class="com.mycomp.service.EngineImpl" />
<bean name="/Engine" autowire="byName"
class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
<property name="service"
ref="com.mycomp.service.EngineImpl" />
<property name="serviceInterface"
value="com.mycomp.client.Engine" />
</bean>
另一种方法是将其添加到web.xml中:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
com.mycomp.engine.config.MyConfigClass
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
上下文配置位置
com.mycop.engine.config.MyConfigClass
org.springframework.web.context.ContextLoaderListener
然后在类MyConfigClass中添加
@配置
在类声明上方,然后将要运行的代码放入类的构造函数中
每种方法的优缺点是什么?有一种方法更好吗?两者都有作用,这里的重点是找到适合您尝试执行的初始化类型的位置,以及您是否真的需要bean或只是为了初始化目的而创建
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
com.mycomp.engine.config.MyConfigClass
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>