Spring - @PostConstruct方法调用了两次

时间:2016-05-31 09:06:51

标签: java spring model-view-controller annotations

这是我的Spring Controller类

@Controller
public class SchedularController{

  @Autowired
  ProjectRepository projectRepository;

  @Autowired
  UtilityRepository utilityRepository;

  @PostConstruct
  public void postconstruct(){
      System.out.println("Starting schedular...");
   }
}

问题是当我启动服务器postconstruct方法运行两次时。

我已经检查了另外一篇文章,主要是说 - “如果你有多个框架管理同一个bean类,就会发生这种情况。例如JSF和CDI,或JSF和Spring,或CDI和Spring等。”

但是我没有使用JSF或CDI并且仍然遇到这个问题。(我的@PostConstruct方法在控制器类中)

如何解决这个问题?

修改 -

这是我的pom文件

<project xmlns="http://maven.apache.org/POM/4.0.0"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0    http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>WBPPM</groupId>
 <artifactId>WBPPM</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>war</packaging>
 <url>http://maven.apache.org</url>

<properties>
    <spring.version>4.0.3.RELEASE</spring.version>
    <spring.security.version>3.0.5.RELEASE</spring.security.version>
    <mongo-java-driver.version>3.0.2</mongo-java-driver.version>
    <spring-data-commons.version>1.7.2.RELEASE</spring-data-commons.version>
    <spring-data-mongodb.version>1.4.2.RELEASE</spring-data-mongodb.version>
    <org.aspectj-version>1.7.4</org.aspectj-version>
    <jackson.databind-version>2.2.3</jackson.databind-version>
    <log4j.version>1.2.17</log4j.version>
    <slf4j.version>1.7.6</slf4j.version>
</properties>

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>

    <!-- Spring Security -->

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>${spring.security.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>${spring.security.version}</version>
    </dependency>

    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!-- <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> 
        <version>${spring.version}</version> </dependency> -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.ws</groupId>
        <artifactId>spring-oxm</artifactId>
        <version>1.5.10</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jettison</groupId>
        <artifactId>jettison</artifactId>
        <version>1.1</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.castor</groupId>
        <artifactId>castor</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>xerces</groupId>
        <artifactId>xercesImpl</artifactId>
        <version>2.8.1</version>
    </dependency>
    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.0</version>
    </dependency>
    <!-- Xstream and Json provider -->
    <dependency>
        <groupId>com.thoughtworks.xstream</groupId>
        <artifactId>xstream</artifactId>
        <version>1.3.1</version>
        <type>jar</type>
    </dependency>
    <!-- Jackson -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.databind-version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>${jackson.databind-version}</version>
    </dependency>

    <!-- Spring / MongoDB -->
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>${mongo-java-driver.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-mongodb</artifactId>
        <version>${spring-data-mongodb.version}</version>
    </dependency>

    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>2.2.2</version>
    </dependency>
    <!-- Tiles plugins -->
    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-jsp</artifactId>
        <version>3.0.3</version>
    </dependency>
    <!-- <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> 
        <version>1.5.11</version> </dependency> -->
    <!-- JSTL plugins -->
    <!-- Log4j -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>${slf4j.version}</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <!-- java mail -->
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.4</version>
    </dependency> 
    <!-- AspectJ -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>${org.aspectj-version}</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>${org.aspectj-version}</version>
    </dependency>
    <dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.6</version>
    </dependency>


    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.2.2</version>
    </dependency>

    <!-- Recaptcha check Api -->
    <dependency>
     <groupId>org.glassfish</groupId>
     <artifactId>javax.json</artifactId>
     <version>1.0.2</version>
    </dependency>

    <!-- Apache Commons Upload -->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>1.3.2</version>
    </dependency>

    <!-- Jasper Report -->
    <!-- <dependency>
        <groupId>net.sf.jasperreports</groupId>
        <artifactId>jasperreports</artifactId>
        <version>5.6.0</version>
    </dependency> -->

    <!-- Freemarker Template -->
    <dependency>
        <groupId>org.freemarker</groupId>
        <artifactId>freemarker</artifactId>
        <version>2.3.20</version>
    </dependency>

    <!-- <dependency>
        <groupId>com.jolbox</groupId>
        <artifactId>bonecp</artifactId>
        <version>0.8.0.RELEASE</version>
    </dependency> -->

    <!-- Excel File Read/write -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.11</version>
    </dependency>

    <!-- amazonaws -->
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk-s3</artifactId>
        <version>1.10.4</version>
    </dependency>

    <!-- Push Notification -->
    <dependency>
        <groupId>com.ganyo</groupId>
        <artifactId>gcm-server</artifactId>
        <version>1.0.2</version>
    </dependency>
    <dependency>
        <groupId>es.arcadiaconsulting.javapns</groupId>
        <artifactId>javapns</artifactId>
        <version>2.2-json</version>
    </dependency>

    <!-- http://mvnrepository.com/artifact/it.sauronsoftware.cron4j/cron4j -->
    <dependency>
        <groupId>it.sauronsoftware.cron4j</groupId>
        <artifactId>cron4j</artifactId>
        <version>2.2.5</version>
    </dependency>



</dependencies> 

<build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.3</version>
            <configuration>
                <warSourceDirectory>WebContent</warSourceDirectory>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
    </plugins>
</build>
</project>

这是我的春天上下文文件 -

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:cxf="http://cxf.apache.org/core" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-1.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">

<context:component-scan base-package="com.wb.ppm" />
<context:annotation-config />
<mvc:annotation-driven />
<aop:aspectj-autoproxy />
<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/**/*" />
        <bean id="webContentInterceptor"
            class="org.springframework.web.servlet.mvc.WebContentInterceptor">
            <property name="cacheSeconds" value="0" />
            <property name="useExpiresHeader" value="true" />
            <property name="useCacheControlHeader" value="true" />
            <property name="useCacheControlNoStore" value="true" />
        </bean>
    </mvc:interceptor>
    <mvc:interceptor>
        <mvc:mapping path="/*" />
        <bean class="com.wb.ppm.util.interceptor.WBInterceptor">
        </bean>
    </mvc:interceptor>
</mvc:interceptors>

<bean id="loggingAspect" class="com.wb.ppm.util.logging.LoggingAspect" />
<bean id="applicationContext" class="com.wb.ppm.security.SpringApplicationContext"
    factory-method="getInstance" />

<bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
</bean>
<bean id="localeResolver"
    class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
    <property name="defaultLocale" value="en" />
</bean>

<bean id="localeChangeInterceptor"
    class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <property name="paramName" value="language" />
</bean>

<bean
    class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
    <property name="interceptors">
        <list>
            <ref bean="localeChangeInterceptor" />
        </list>
    </property>
</bean>
<!-- Register the welcome.properties -->
<bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="ApplicationResources" />
</bean>

<!-- Factory bean that creates the Mongo instance -->
<context:property-placeholder location="classpath:mongodb.properties"
    order="1" />

<bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
    <property name="host" value="${mongo.host.name}" />
    <property name="port" value="${mongo.host.port}" />
</bean>


<bean id="mongoDbFactory" class="org.springframework.data.mongodb.core.SimpleMongoDbFactory">
    <constructor-arg name="mongo" ref="mongo" />
    <constructor-arg name="databaseName" value="${mongo.db.name}" />
</bean>


<mongo:mapping-converter id="converter" />
<bean name="gridFsTemplate"
    class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
    <constructor-arg ref="mongoDbFactory" />
    <constructor-arg ref="converter" />
</bean>

<bean id="userCredentials" class="org.springframework.data.authentication.UserCredentials">
    <constructor-arg name="username" value="${mongo.db.username}" />
    <constructor-arg name="password" value="${mongo.db.password}" />
</bean>

<!-- MongoConverter for converting the dot in map key to \+ in mongodb  -->
<bean id="mongoMoxydomainConverter" class="org.springframework.data.mongodb.core.convert.MappingMongoConverter">
    <constructor-arg index="0" ref="mongoDbFactory" />
    <constructor-arg index="1">
        <bean class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" />
    </constructor-arg>
    <property name="mapKeyDotReplacement" value="\\+"/>
</bean>


<!-- MongoTemplate for connecting and querying the documents in the database -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
    <constructor-arg name="mongoConverter" ref="mongoMoxydomainConverter"/>
    <!-- <constructor-arg name="userCredentials" ref="userCredentials" /> -->
</bean>

<!-- Use this post processor to translate any MongoExceptions thrown in 
    @Repository annotated classes -->
<bean
    class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

<!-- Register the welcome.properties -->
<bean id="tilesConfigurer"
    class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
    <property name="definitions">
        <list>
            <value>/WEB-INF/tiles.xml</value>
        </list>
    </property>
</bean>

<bean id="tilesviewResolver"
    class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.tiles3.TilesView" />
    <property name="order" value="2"></property>
</bean>

<bean id="jstlviewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/pages/" />
    <property name="suffix" value=".jsp" />
    <property name="order" value="3"></property>
</bean>

<!-- Configure to plugin JSON as request and response in method handler -->
<bean
    class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jsonMessageConverter" />
            <ref bean="xmlMessageConverter" />
        </list>
    </property>
</bean>

<bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
</bean>

<!-- Configure bean to convert JSON to POJO and vice versa -->
<bean id="jsonMessageConverter"
    class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    <property name="supportedMediaTypes" value="application/json" />
</bean>
<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="150000000"/>
    <property name="maxInMemorySize" value="150000000"/>
</bean>

<bean id="xmlMessageConverter"
    class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
    <property name="marshaller" ref="castorMarshaller" />
    <property name="unmarshaller" ref="castorMarshaller" />
    <property name="supportedMediaTypes" value="application/xml" />
</bean>
<bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller">
</bean>
<bean id="simpleMappingExceptionResolver"
    class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <map>
            <entry key="NotAuthorizedException" value="redirect:/login" />
        </map>
    </property>
    <property name="defaultErrorView" value="redirect:/pages/error/globalError.jsp" />
</bean>

这是我的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>WorldBankPPM</display-name>
<!-- Spring Listeners -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:worldbank-context.xml
        classpath:security-applicationContext.xml
    </param-value>
</context-param>
<context-param>
    <param-name>log4j-config-location</param-name>
    <param-value>src/log4j.properties</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/classes/worldbank-context.xml</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
    <url-pattern>/login</url-pattern>
</servlet-mapping>
<session-config>
    <session-timeout>360</session-timeout>
</session-config>
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/assets/*</url-pattern>
    <url-pattern>/vendor/*</url-pattern>
</servlet-mapping>
<servlet>
    <servlet-name>jsp</servlet-name>
    <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
    <init-param>
        <param-name>fork</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>xpoweredBy</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>mappedfile</param-name>
        <param-value>false</param-value>
    </init-param>
    <load-on-startup>3</load-on-startup>
</servlet>
<error-page>
    <error-code>404</error-code>
    <location>/pages/error/error404.jsp</location>
</error-page>
<error-page>
    <error-code>500</error-code>
    <location>/pages/error/globalError.jsp</location>
</error-page>
<!-- <security-constraint>
    <web-resource-collection>
        <web-resource-name>securedapp</web-resource-name>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint> -->

1 个答案:

答案 0 :(得分:0)

几天前我也遇到了同样的问题,我已经成功解决了这个问题。

就我而言,我已经使用Spring starter创建了应用程序。

在Eclipse或任何IDE中导入项目时,您会看到主包中有两个类:

  1. ServletInitializer.java ,它扩展了SpringBootServletInitializer并覆盖了configure(),当我们创建 war 文件并在tomcat下运行时,它将被调用服务器

  2. YourApplication.java 包含main(),这是在本地服务器上运行/调试应用程序时进入我们应用程序的入口。

我已参考this创建战争文件并进行必要的更改。

问题是我忘记删除ServletInitializer.java,它也包含相同的方法,这是初始化两次的主要原因。

一旦从该文件中删除了多余的代码,Spring Boot将只初始化一次上下文,并且能够执行一次代码。