I am unable to make static images visible in Spring MVC application.
If I add
<mvc:resources mapping="/images/**" location="/images/" />
into dispatcher-servlet.xml or applicationContext.xml then I am loosing an ability to execute controllers.
My current dispatcher-servlet.xml is follows:
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.inthemoon.snippets.springmvc" />
<mvc:resources mapping="/images/**" location="/images/" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
When I am opening /hello URL I am getting an error in log:
org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/hello] in DispatcherServlet with name 'dispatcher'
If I remove resources directive, I see the following messages in the log:
04-Dec-2015 22:30:15.687 INFO [RMI TCP Connection(3)-127.0.0.1] org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions Loading XML bean definitions from ServletContext resource [/WEB-INF/dispatcher-servlet.xml]
04-Dec-2015 22:30:16.012 INFO [RMI TCP Connection(3)-127.0.0.1] org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping.registerHandler Mapped URL path [/hello] onto handler 'helloWorldController'
04-Dec-2015 22:30:16.013 INFO [RMI TCP Connection(3)-127.0.0.1] org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping.registerHandler Mapped URL path [/hello.*] onto handler 'helloWorldController'
04-Dec-2015 22:30:16.013 INFO [RMI TCP Connection(3)-127.0.0.1] org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping.registerHandler Mapped URL path [/hello/] onto handler 'helloWorldController'
These messages are absent if resources directive is present.
You have to insert <mvc:annotation-driven> if you want to use the <mvc:resources ...> statement.
See for more details the following question & answer: Using mvc:resources problem
Related
I get an exception when I try to make deploy using Maven. That exception shows:
java.lang.NoSuchMethodError: add
Here my stacktrace:
User defined listener
org.springframework.web.context.ContextLoaderListener failed:
org.springframework.beans.factory.BeanDefinitionStoreException:
Unexpected exception parsing XML document from ServletContext resource
[/WEB-INF/dispatcher-servlet.xml]; nested exception is
java.lang.NoSuchMethodError: add.
org.springframework.beans.factory.BeanDefinitionStoreException:
Unexpected exception parsing XML document from ServletContext resource
[/WEB-INF/dispatcher-servlet.xml]; nested exception is
java.lang.NoSuchMethodError: add
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:420)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:342)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:92)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:123)
Also posting the dispatcher_servelet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="com.mycompany.site.web" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix"><value>/WEB-INF/jsp/</value></property>
<property name="suffix"><value>.jsp</value></property>
</bean>
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
I got it!
I should put the following code, in the weblogic.xml file:
<container-descriptor>
<prefer-web-inf-classes>true</prefer-web-inf-classes>
</container-descriptor>
I'm with a JEE project, from Maven project to Dynamic Web.
The problem is that I haven't use xml configuration, but now, with the Dynamic web project, I must.
I can't figure out how write right the applicationContext.xml; I've read a lot of topic but no one help me.
Here the code and error:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:sec="http://www.springframework.org/schema/security"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.2.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-4.2.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">
<!-- Abilita l'uso di tutte le annotazioni -->
<context:annotation-config/>
<import resource="security-config.xml"/>
<context:component-scan base-package="it.**"/>
<!-- Abilita il supporto AOP -->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<util:properties id="settings" location="classpath:../../META-INF/MANIFEST.MF"/>
<!-- i valori delle properties vengono iniettati in AuthentificationFilter e il id=myProps serve per l'iniezione -->
<util:properties id="myProps" location="classpath:muru/application.properties"/>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:muru/*.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg>
<bean class="com.mongodb.MongoClient">
<constructor-arg value="localhost"/>
<constructor-arg value="27017"/>
</bean>
</constructor-arg>
<constructor-arg value="database"/>
</bean>
<mongo:repositories base-package="it.cap.domain" mongo-template-ref="mongoTemplate"></mongo:repositories>
<!-- Abilita la configurazione delle transazioni tramite annotazioni -->
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
</beans>
Stacktrace
11:12:26.108 [localhost-startStop-1] ERROR org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 68 in XML document from ServletContext resource [/WEB-INF/applicationContext.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 68; columnNumber: 93; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'mongo:repositories'.
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:399)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'mongo:repositories'.
Can you help me to understand?
Thanks in advice :)
The issue seems to be from the order of the bean definition in your context file.
Just try changing the position of the below bean definition
<tx:annotation-driven transaction-manager="txManager"/>
from currrent position to just after the below bean.
<context:component-scan base-package="it.**"/>
Something like
<context:component-scan base-package="it.**"/>
<tx:annotation-driven transaction-manager="txManager"/>
See if this solves your issue.
For your reference..
http://forum.spring.io/forum/spring-projects/container/9895-order-of-bean-definitions-matters
If the above solution doesn't works ,last thing I guess would be to check if right jars holding the specified mongo related xsds under your application's lib folder
I found a solution, in applicationContext.xml I just put an import tag to resource "spring.xml":
<import resource="spring.xml" />
And inside spring.xml:
<!-- MongoDB host -->
<mongo:mongo host="localhost" port="27017" />
<!-- Template for performing MongoDB operations -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate" c:mongo-ref="mongo" c:databaseName="dbname" />
<!-- Activate Spring Data MongoDB repository support -->
<mongo:repositories base-package="it.domain" mongo-template-ref="mongoTemplate" />
<!-- Use this post processor to translate any MongoExceptions thrown in #Repository annotated classes -->
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
Now it starts without tomcat's crash; I wil let you know if it works fine with db's connections.
I am trying to deploy a Spring 3 MVC Rest Application on WebSphere Application Server 8.0 and have not had any success.
Here is my controller class
`
#Controller
public class BookingService {
public BookingService() {
System.out.println("test");
}
#RequestMapping(value="/test", method=RequestMethod.GET, produces="application/xml")
#ResponseBody
public String test() {
return "<test>test</test>";
}
}
`
web.xml - servlet spec 3
`
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
</web-app>
`
dispatcher-servlet.xml
`
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
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://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.example" />
<!-- <tx:annotation-driven /> -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean id="viewResolver" class=
"org.springframework.web.servlet.view.BeanNameViewResolver" />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="html" value="text/html" />
<entry key="json" value="application/json" />
<entry key="json" value="application/xml" />
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="prefixJson" value="true" />
</bean>
</list>
</property>
</bean>
</beans>
`
I confirm that it does work on tomcat. In the tomcat logs the mapping is being created.
INFO: Mapped "{[/test],methods=[GET],params=[],headers=[],consumes=[],produces=[application/xml],custom=[]}" onto public java.lang.String com.westjet.ens.services.BookingService.test()
Doing a curl on http://localhost:8080/ens-das-web/api/test returns HTTP 200.
However in the was logs this does not appear and doing a curl http://localhost:9080/my-service-web/api/test returns 404 and the following response.
`
Error 404: SRVE0295E: Error reported: 404
`
Also the WAS Log shows the following when doing a curl.
[9/23/15 15:53:21:390 MDT] 00000089 PageNotFound W org.springframework.web.servlet.DispatcherServlet noHandlerFound No mapping found for HTTP request with URI [/ens-das-web/api/test] in DispatcherServlet with name 'dispatcher'
WAS logs:
[9/23/15 15:20:52:809 MDT] 00000049 WASSessionCor I SessionContextRegistry getSessionContext SESN0176I: Will create a new session context for application key default_host/ens-das-web
[9/23/15 15:20:58:993 MDT] 00000049 webapp I com.ibm.ws.webcontainer.webapp.WebApp log SRVE0292I: Servlet Message - [ens-das-web-0_1_war#ens-das-web-0.1.war]:.No Spring WebApplicationInitializer types detected on classpath
[9/23/15 15:20:59:176 MDT] 00000049 webapp I com.ibm.ws.webcontainer.webapp.WebApp log SRVE0292I: Servlet Message - [ens-das-web-0_1_war#ens-das-web-0.1.war]:.Initializing Spring FrameworkServlet 'dispatcher'
[9/23/15 15:20:59:178 MDT] 00000049 DispatcherSer I org.springframework.web.servlet.FrameworkServlet initServletBean FrameworkServlet 'dispatcher': initialization started
[9/23/15 15:20:59:229 MDT] 00000049 XmlWebApplica I org.springframework.context.support.AbstractApplicationContext prepareRefresh Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Wed Sep 23 15:20:59 MDT 2015]; root of context hierarchy
[9/23/15 15:20:59:313 MDT] 00000049 XmlBeanDefini I org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions Loading XML bean definitions from ServletContext resource [/WEB-INF/dispatcher-servlet.xml]
[9/23/15 15:20:59:749 MDT] 00000049 AutowiredAnno I org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init> JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
[9/23/15 15:20:59:770 MDT] 00000049 DefaultListab I org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#3c2306c: defining beans [mvcContentNegotiationManager,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0,org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0,viewResolver,org.springframework.web.servlet.view.ContentNegotiatingViewResolver#0,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
[9/23/15 15:21:00:615 MDT] 00000049 DispatcherSer I org.springframework.web.servlet.FrameworkServlet initServletBean FrameworkServlet 'dispatcher': initialization completed in 1436 ms
[9/23/15 15:21:00:615 MDT] 00000049 servlet I com.ibm.ws.webcontainer.servlet.ServletWrapper init SRVE0242I: [ens-das-web-0_1_war] [/ens-das-web] [dispatcher]: Initialization successful.
[9/23/15 15:21:00:616 MDT] 00000049 webcontainer I com.ibm.ws.webcontainer.VirtualHostImpl addWebApplication SRVE0250I: Web Module ENS Data Access Service has been bound to default_host[*:9080,*:80,*:9443,*:5060,*:5061,*:443].
Any help would be much appreciated.
I was able to fix this. For some reason maven was not cleaning the WEB-INF/classes folder and my #Controller class was not available.
Couldn't find what is wrong with inserting data in mySQL database using Spring data, JPA, hibernate and mySQL. It is inserting data twice in database.
The root-context.xml file is:
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.8.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<context:component-scan base-package="com.project.db">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<jdbc:embedded-database type="HSQL" id="dataSource"/>
<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/jpa"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean> -->
<!-- <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="MYSQL"/>
</bean> -->
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
id="entityManagerFactory">
<property name="packagesToScan" value="com.project.db.entity"></property>
<property name="dataSource" ref="dataSource"></property>
<!-- <property name="jpaVendorAdapter" ref="jpaVendorAdapter"/> -->
<property name="jpaProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<jpa:repositories base-package="com.project.db.repository"/>
</beans>
The servlet-context.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.project.db" />
</beans:beans>
My #Entity class is:
#Entity
public class User {
#Id
#GeneratedValue
private Integer id ;
private String name ;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
JPA repository is:
import org.springframework.data.jpa.repository.JpaRepository;
import com.project.entity.User;
public interface UserRepository extends JpaRepository<User, Integer> {
}
And, finally, #Service class is:
import javax.annotation.PostConstruct;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.project.entity.User;
import com.project.repository.UserRepository;
#Transactional
#Service
public class InitDbService {
#Autowired
private UserRepository userRepository;
#PostConstruct
public void init() {
User user = new User();
user.setName("Ali");
userRepository.save(user);
}
}
The above code works without errors/exceptions; database/table is also created but data is inserted into Entity/table twice when I see that in mySQL database.
Project is at github.
Console output is:
INFO: Spring WebApplicationInitializers detected on classpath: [com.project.db.WebAppInitializer#1867584]
Sep 2, 2015 12:50:17 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Wed Sep 02 12:50:17 PKT 2015]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/root-context.xml]
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Hibernate: drop table if exists users
Hibernate: create table users (id integer not null auto_increment, name varchar(255), primary key (id))
Hibernate: insert into users (name) values (?) // first time inserting here and
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 5633 ms
Sep 2, 2015 12:50:23 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'springDispatcher'
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'springDispatcher': initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing WebApplicationContext for namespace 'springDispatcher-servlet': startup date [Wed Sep 02 12:50:23 PKT 2015]; parent: Root WebApplicationContext
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.project.db.HomeController.home(java.util.Locale,org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - Looking for #ControllerAdvice: WebApplicationContext for namespace 'springDispatcher-servlet': startup date [Wed Sep 02 12:50:23 PKT 2015]; parent: Root WebApplicationContext
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - Looking for #ControllerAdvice: WebApplicationContext for namespace 'springDispatcher-servlet': startup date [Wed Sep 02 12:50:23 PKT 2015]; parent: Root WebApplicationContext
INFO : org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/resources/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0'
Hibernate: insert into users (name) values (?) // Second time inserting here
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'springDispatcher': initialization completed in 1483 ms
Sep 2, 2015 12:50:25 PM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/db] is completed
Taking a chance here since I see that you are using Spring MVC.
With Spring MVC, you have a servlet-context which defines the controllers, and an applicationContext for other beans. It might be that you are scanning for beans other than controllers in the servlet-context, which in turn will give you two beans of InitDbService, both running their #PostConstruct-method, inserting into the database.
This can be solved by defining component-scan like this:
servlet-context (after placing controllers and controllers only in a separate package):
<context:component-scan base-package="com.my.project.controller" />
applicationContext:
<context:component-scan base-package="com.my.project">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
You have to enable DEBUG logging to check that your initailizing bean isn't created twice, as Tobb mentioned before your bean is probabbly created in both contexts. Log stands clearly that first insert is executed during root context initialization (witch is correct) and second time during servlet context initialization (which is wrong)
I have found solution to your problem: You have to add commponent scan without default filters to your root-context
<context:component-scan base-package="com.project.db" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
and servlet-context is
<context:component-scan base-package="com.project.db" />
I have tested your project and its working fine with this change.
I got this error when i restart the tomcat "Context initialization failed"
[ERROR][2013-02-26 15:48:49,432][ContextLoader] - [Context initialization failed]
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from relative location [applications\applications.xml]
Offending resource: ServletContext resource [/WEB-INF/config/context/appContext.xml]; nested exception is org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from relative location [..\..\..\..\schema\ab- products\common\resources\appContext-services.xml]
Offending resource: ServletContext resource [/WEB-INF/config/context/applications/applications.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/schema/ab-products/common/resources/appContext-services.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/schema/ab-products/common/resources/appContext-services.xml]
Here is appContext-services.xml,it exists in /schema/ab-products/common/resources/appContext-services.xml
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd">
<!-- ========================= Start of SERVICE DEFINITIONS ========================= -->
<!--
Per-activity configuration bean.
-->
<bean id="AbCommonResources-configuration"
class="com.archibus.service.cost.Configuration">
<property name="defaultDateStart" value="1980-01-01" />
<property name="defaultDateEnd" value="2099-12-31" />
</bean>
<!--
Remote version of CostService. This service is not used when the client calls WFRs.
TODO: fix proxyInterfaces="com.archibus.utility.Immutable": define and use ICostService interface.
-->
<bean id="CostService-remote"
class="org.springframework.aop.framework.ProxyFactoryBean"
p:proxyInterfaces="com.archibus.utility.Immutable"
p:target-ref="CostService">
<property name="interceptorNames">
<list>
<value>securityInterceptor</value>
<value>exceptionHandlingInterceptor</value>
</list>
</property>
</bean>
<!--
Local version of CostService, used by WFRs.
-->
<bean id="CostService"
class="com.archibus.service.cost.CostService"
scope="prototype"
p:configuration-ref="AbCommonResources-configuration">
</bean>
<!--
Cost beans.
-->
<bean id="actualCost"
class="com.archibus.app.common.finance.domain.ActualCost"
scope="prototype">
</bean>
<bean id="scheduledCost"
class="com.archibus.app.common.finance.domain.ScheduledCost"
scope="prototype">
</bean>
<bean id="recurringCost"
class="com.archibus.app.common.finance.domain.RecurringCost"
p:configuration-ref="AbCommonResources-configuration"
scope="prototype">
</bean>
here is applications.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<import resource="..\..\..\..\schema\ab-products\common\resources\appContext-services.xml" />
thank you for your response, i solve this issue. It s about to java version. I changed my java version 1.4 to 1.6 so now there is no problem.
Goodness - here's your problem:
java.io.FileNotFoundException: Could not open ServletContext resource [/schema/ab-products/common/resources/appContext-services.xml]
Spring couldn't find that app context XML in the CLASSPATH.
Check the location and the way you've declared it in the web.xml. One or both are wrong.
the problem might be the your xml file location
FileNotFoundException means it is unable to find the file in that path.
The stack error is pretty clear .
Context initialization fails when it loads the
/WEB-INF/config/context/applications/applications.xml
I gues you import following file ,
/schema/ab-products/common/resources/appContext-services.xml
move the file to
/WEB-INF/config/context/applications/ and update you import statement in applications.xml
The problem appears to be:
nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/schema/ab-products/common/resources/appContext-services.xml] at
Is appContext-services.xml present in the specified location, and readable (ie has the right permissions)?