I have some legacy Spring MVC code mixed with gwt code in same artifact (built using maven) and I cannot make it run. It wants validation provider at runtime which i do not need (since I'm not using any JSR-303 validation annotations) and do not want in CP (it may conflict with some app containers this artifact will be deployed in)
How to force spring not to do any JSR-303 validations and get rid of runtime dependency on validation provider?
PS artifact has validation-api in CP since GWT is using it somehow
PPS
Seems like removing <mvc:annotation-driven/> from Spring config fixes this.
Binding and classic validations still works (I have <context:annotation-config/> enabled)
As you already discovered, <mvc:annotation-driven/> sets a lot of features including JSR-303. The equivalent is
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="order" value="0" />
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="validator" ref="validator" />
</bean>
</property>
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
<bean class="org.springframework.http.converter.FormHttpMessageConverter" />
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
<bean id="conversion-service"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />
So you may substitute the tag onto this xml configuration and remove parts you don't need.
Related
First of all I have to say, that I am an absolute beginner in developing Spring Application. What I try to do is to switch the locale from 'en' to 'de'. For this I found the configuration below witch I put in my mvc-dispatcher-servlet.xml
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="Messages" />
</bean>
<!-- Localization Start -->
<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>
After that I expect that I can change the locale by adding '?language=de' behind a existing URL. So the request 'http://localhost:8080/?language=de' should switch the locale. This didn’t work. The website is shown in the defined default language
My property files are located in /src/main/resources. The names are “Messages_en.propperties” and “Messages_de.propperties”. If I switch the default language to “de”, the correct language file is loaded and the website is shown in german.
Has someone an idea what’s wrong in my configuration?
I believe you have to register the LocaleChangeInterceptor with an interceptor in Spring
<!-- Declare the Interceptor -->
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"
p:paramName="locale" />
</mvc:interceptors>
The LocaleChangeInterceptor is configured to look for the parameter name 'locale' to indicate a change of the user's locale, and is registered as an interceptor using the Spring MVC Namespace. For example, adding 'locale=es' to a URL would change the locale to Spanish.
I am using spring-data-neo4j for my neo4j database in my application,i want to have transactional APIs in my service layer but it seems that #transaction is not working.
Service Layer:
#Transactional('neo4jTransactionManager')
def savePerson(){
Person person=new Person()
person.setName("prabh")
person.setDistance(100)
PersonRepository.save(person)
int i=10/0;
}
Configuration :
<context:component-scan base-package="neo4j"></context:component-scan>
<bean id="graphDatabaseService"
class="org.springframework.data.neo4j.rest.SpringRestGraphDatabase">
<constructor-arg value="http://localhost:7474/db/data" />
</bean>
<neo4j:config graphDatabaseService="graphDatabaseService"
base-package="neo4j" />
<neo4j:repositories base-package="neo4j" />
<bean id="neo4jTransactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManager">
<bean class="org.neo4j.kernel.impl.transaction.SpringTransactionManager">
<constructor-arg ref="graphDatabaseService" />
</bean>
</property>
<property name="userTransaction">
<bean class="org.neo4j.kernel.impl.transaction.UserTransactionImpl">
<constructor-arg ref="graphDatabaseService" />
</bean>
</property>
</bean>
<tx:annotation-driven mode="aspectj"
transaction-manager="neo4jTransactionManager" />
</beans>
I am using rest server of neo4j database.
That's what the documentation says, for remote access there is no transactionality due to Neo4j's REST API not exposing transactions over the wire in the past
In the next milestone (and the current 3.3.0.BUILD-SNAPSHOT) build a new remoting integration is used, which exposes transactions over the wire and is also much faster than the existing one.
I have a standalone java app that now runs an embedded Jetty server to expose a RESTful API for HTTP. It does make heavy use of Spring beans for everything from Hibernate to Jetty. I have Jetty configured with a DispatcherServlet ( the thought being that adding a non-REST API in the future will be as simple as making the new Controller and mapping it correctly for the dispatcher).
My app has a class with a main method that creates a ClassPathXmlApplicationContext from my appContext.xml to start everything up.
ApplicationContext ac= new ClassPathXmlApplicationContext(new String[] { "appContext.xml" });
I don't know how to make beans defined in the context config file for the DispatcherServlet have access to beans defined in the appContext.xml where jetty is defined. My Jetty definition looks like this:
<bean id="JettyServer" class="org.eclipse.jetty.server.Server" init-method="start" destroy-method="stop">
<constructor-arg>
<bean id="threadPool" class="org.eclipse.jetty.util.thread.QueuedThreadPool">
<property name="minThreads" value="2"/>
<property name="maxThreads" value="10"/>
</bean>
</constructor-arg>
<property name="connectors">
<list>
<bean id="Connector" class="org.eclipse.jetty.server.ServerConnector">
<constructor-arg ref="JettyServer"/>
<property name="port" value="8090"/>
</bean>
</list>
</property>
<property name="handler">
<bean id="handlers" class="org.eclipse.jetty.server.handler.HandlerCollection">
<property name="handlers">
<list>
<bean class="org.eclipse.jetty.servlet.ServletContextHandler">
<property name="contextPath" value="/"/>
<property name="servletHandler">
<bean class="org.eclipse.jetty.servlet.ServletHandler">
<property name="servlets">
<list>
<bean class="org.eclipse.jetty.servlet.ServletHolder">
<property name="name" value="DefaultServlet"/>
<property name="servlet">
<bean class="org.springframework.web.servlet.DispatcherServlet"/>
</property>
<property name="initParameters">
<map>
<entry key="contextConfigLocation" value="classpath:./DefaultServlet.xml" />
</map>
</property>
</bean>
</list>
</property>
<property name="servletMappings">
<list>
<bean class="org.eclipse.jetty.servlet.ServletMapping">
<property name="pathSpecs">
<list><value>/</value></list>
</property>
<property name="servletName" value="DefaultServlet"/>
</bean>
</list>
</property>
</bean>
</property>
</bean>
<bean class="org.eclipse.jetty.server.handler.RequestLogHandler">
<property name="requestLog">
<bean class="org.eclipse.jetty.server.NCSARequestLog">
<constructor-arg value="/opt/impulse/logs/jetty-yyyy_mm_dd.log"/>
<property name="extended" value="false" />
</bean>
</property>
</bean>
</list>
</property>
</bean>
</property>
</bean>
Then in DefaultServlet.xml I try to defined a bean with a property references a bean defined in appContext.xml, which is what breaks.
<bean id="restApiController" class="com.mycompany.myapp.api.controllers.RESTfulController">
<property name="someBean" ref="someBean"/>
</bean>
You are bootstrapping Jetty with applicationContext.xml, which in turn sets up jetty with your servlet configuration. Inside it you are configuring your servlet with the contextConfigLocation parameter pointing to the servlet application context. It will still run as a webapp, even if you embed it. So you need to provide your servlet with the config to your other beans as well. I suggest that you extract the jetty setup into it's own file, and then the rest of your beans in a different file. You then supply the other context file in the contextConfigLocation.
Edit
If you really need to share the application context between jetty and your servlet, maybe you can use some of the information in this blog. It seems to be possible, but it looks like you have to wire up the parent/child relationship between the contexts manually.
For me, what worked is setting of ResourceConfig. With DispatcherServlet server was not even able to serve Rest call. So I used ServletContainer. Now Rest call worked but not able to access beans loaded in ApplicationContext. There ResourceConfig registration helped. Below was my configuration that I came up after long R & D. I had Jetty version 9.2.11.v20150529 and Spring 4.1.2.RELEASE
<bean class="org.eclipse.jetty.servlet.ServletHolder">
<property name="name" value="DefaultServlet"/>
<property name="servlet">
<bean id="servletContainer" class="org.glassfish.jersey.servlet.ServletContainer">
<constructor-arg>
<ref bean="config" />
</constructor-arg>
</bean>
</property>
</bean>
<bean id="config" class="org.glassfish.jersey.server.ResourceConfig" />
Basically I set ResourceConfig under ServletContainer. Then in application, I fetched all beans loaded in my applicationContext and register with this Resource config like below
ResourceConfig restConfig = (ResourceConfig)webContext.getBean("config");
String[] beans = context.getBeanDefinitionNames();
for(String bean : beans)
restConfig.registerInstances(context.getBean(bean));
Well, webContext here is WebAppContext which is required instead of ServletContaxtHandler. So instead of below lines as mentioned in question
<bean class="org.eclipse.jetty.servlet.ServletContextHandler">
<property name="contextPath" value="/"/>
I have
<!-- To work with Spring , we need WebAppContext instead of ServletContext -->
<!-- <bean id="servletContextHandler" class="org.eclipse.jetty.servlet.ServletContextHandler"> -->
<constructor-arg name="webApp" value="./target/classes/" />
<constructor-arg name="contextPath" value="/" />
I want to configure AnnotationMethodHandlerExceptionResolver by adding jackson message converter. The problem is that I have already configured message converters in <mvc:message-converters> by creating a bean, and I can't reference it in AnnotationMethodHandlerExceptionResolver neither use ref in <mvc:message-conferters>
<mvc:annotation-driven>
<mvc:message-converters register-defaults="false">
<bean id="mappingJackson2" class="pl.styall.scylla.json.config.CustomMappingJackson2">
<property name="objectMapper" ref="jacksonObjectMapper" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="outboundExceptionAdapter"
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
<property name="messageConverters">
<list>
<ref bean="mappingJackson2" />
</list>
</property>
</bean>
I could define two beans one for <mvc:message-converters> and AnnotationMethodHandlerExceptionResolver, but it is probably not the best idea. Is there other way to do this?
This is not supported yet, but it is on the 3.2 backlog. So it might be supported in 3.2.
See Add support for <ref> in addition to <bean> for <mvc:message-converters> for the Spring feature request.
I'm trying to add one more database/schema/persistenceUnit in my project and I'm receiving the error:
No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 2
I google/api allot and could not found why spring is complaining about my configuration.
Here is part of my applicationContext.xml
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="transactionManager" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="${show.hibernate.sql}" />
<property name="generateDdl" value="false" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
</bean>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${database.driver}" />
<property name="url" ...
<property name="testOnBorrow" value="true" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="entityManagerFactoryREST" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSourceREST" />
<property name="persistenceUnitName" value="REST" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="${show.hibernate.sql}" />
<property name="generateDdl" value="false" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
</bean>
</property>
</bean>
<bean id="dataSourceREST" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${database.driver}" />
...
<property name="testOnBorrow" value="true" />
</bean>
<bean id="transactionManagerREST" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryREST" />
</bean>
<tx:annotation-driven transaction-manager="REST"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
Some questions:
Do I need to have two tx:annotation-driven ?
Do I need to specify persistenceUnitName in the factory ?
I'm putting some notes of my digg in spring forum (LINK)
Well thats it... any help will be glad!
With Spring, you need to have only one EntityManagerFactory.
What you are looking for is describe in the Spring documentation at the chapiter 13.5.1.4 : "Deals with multiple persitence units"
I copy/paste the text :
"13.5.1.4 Dealing with multiple persistence units
For applications that rely on multiple persistence units locations, stored in various JARS in the classpath, for example, Spring offers the PersistenceUnitManager to act as a central repository and to avoid the persistence units discovery process, which can be expensive. The default implementation allows multiple locations to be specified that are parsed and later retrieved through the persistence unit name. (By default, the classpath is searched for META-INF/persistence.xml files.)
<bean id="pum" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>org/springframework/orm/jpa/domain/persistence-multi.xml</value>
<value>classpath:/my/package/**/custom-persistence.xml</value>
<value>classpath*:META-INF/persistence.xml</value>
</list>
</property>
<property name="dataSources">
<map>
<entry key="localDataSource" value-ref="local-db"/>
<entry key="remoteDataSource" value-ref="remote-db"/>
</map>
</property>
<!-- if no datasource is specified, use this one -->
<property name="defaultDataSource" ref="remoteDataSource"/>
</bean>
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="pum"/>
<property name="persistenceUnitName" value="myCustomUnit"/>
</bean>
The default implementation allows customization of the PersistenceUnitInfo instances, before they are fed to the JPA provider, declaratively through its properties, which affect all hosted units, or programmatically, through the PersistenceUnitPostProcessor, which allows persistence unit selection. If no PersistenceUnitManager is specified, one is created and used internally by LocalContainerEntityManagerFactoryBean."
This exceptions means that you are trying to autowire EntityManagerFactory by type. Do you have any #Autowired annotation in your code?
Aslo, when using #PersistenceContext, set the unit attribute correctly. And (I'm not sure if this is a proper thing to do) - try setting the name attribute to your respective factory name.
Also, check if you haven't copy-pasted incorrectly the REST transaction manager - now there is no such bean REST
Ensure all of your #PersistenceContext specify unitName. I haven't figured out how to tell Spring that a particular EMF or PersistenceUnit is the default. I thought specifying primary="true" on the default EMF would work but doesn't appear to
Do I need to specify persistenceUnitName in the factory ?
If you've got multiple persistence units, you do need to specify which ones the factories will use.
More to the heart of the matter, see SPR-3955. To summarize, versions prior to Spring 3.0M4 do not support multiple transaction managers with #Transactional. Nor do I believe it honors the "unitName" attribute for #PersistenceContext, so you can't specify that either.
For an example of how I worked around this by explicitly injecting EntityManagerFactorys and using AOP to re-enable #Transactional, see my sample app