I am new to spring framework. I want to use spy memcached in my application, but i cant find the proper annotation based configuration to set the bean. Currently i am using Memcached static object in my Controller which looks really bad programming. Please provide a simple way to implement memcache in spring configuration. just on default values of memcached "127.0.0.1:11211". Thank you.
edit.
how to convert this xml cinfiguration into proper annitation based config and what to Autowire in cintroller..
<bean name="defaultMemcachedClient" class="com.google.code.ssm.CacheFactory">
<property name="cacheClientFactory">
<bean name="cacheClientFactory" class="com.google.code.ssm.providers.spymemcached.Mem
</property>
<property name="addressProvider">
<bean class="com.google.code.ssm.config.DefaultAddressProvider">
<property name="address" value="127.0.0.1:11211" />
</bean>
</property>
<property name="configuration">
<bean class="com.google.code.ssm.providers.CacheConfiguration">
<property name="consistentHashing" value="true" />
</bean>
</property>
</bean>
Take a look at Simple Spring Memcached (SSM) library.
It provides integration to memcached (via spymemcached or xmemcached client) using:
Spring Cache annotations (#Cacheable)
custom annotations (like ReadThroughSingleCache).
Related
I have been surfing on Internet for hours trying to find a good example to configure a Spring's repository by using the XML instead of annotations (#Repository).
I found some good stuff (Hibernate 3):
<!-- Hibernate interceptor to manage the session outside any transaction scope. -->
<bean id="hibernateInterceptor"
class="org.springframework.orm.hibernate3.HibernateInterceptor">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- The configuration DAO -->
<bean id="configurationDAO"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="configurationDAOTarget"/>
<property name="proxyInterfaces" value="org.itracker.persistence.dao.ConfigurationDAO"/>
<property name="interceptorNames">
<list>
<value>hibernateInterceptor</value>
</list>
</property>
</bean>
<bean id="configurationDAOTarget"
class="org.itracker.persistence.dao.ConfigurationDAOImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
But it seems that Hibernate 4 does not support HibernateInterceptor any longer.
Have any of you experience with this issue? A good solution? There's no other option rather than using the annotation?
Thanks in advance.
All #Repository does is meta-annotate a #Component and let the org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor create an AOP proxy which does exception translation. At that level it's all Hibernate independent. The different implementations then understand their own exceptions and translate to the common Spring DataAccessException hierarchy.
In terms of doing it with XML, you'd have to somehow apply that proxy to the DAO beans you care about. Take a look at the reference manual for that, but it's going to be painful and not win you much.
For the sake of completeness, you can change the annotation from #Repository to something else, but as I read your question, you don't want to use annotations at all.
Currently i am using spring 2.5 XML based configuration for bean. Now i want to upgrade it to Spring 3.x. I want to know after upgrading to 3.x my old XML configuration will work or not. If works then can i write annotation based configuration for new work in my current project.
Example of XML configuration:
<bean id="addTestimonialController" class="com.eam.web.testimonial.AddTestimonialController" singleton="true">
<property name="branchManager" ref="branchMan"/>
<property name="userManager" ref="userMan"/>
<property name="itemManager" ref="itemMan"/>
<property name="vendorManager" ref="vendorMan"/>
<property name="categoryManager" ref="categoryMan"/>
<property name="lineupManager" ref="lineupMan"/>
<property name="testimonialManager" ref="testimonialMan"/>
<property name="categoryMenuManager" ref="categoryMenuMan"/>
<property name="setManager" ref="setMan"/>
<property name="configurationManager" ref="configMan"/>
<property name="cartManager" ref="cartMan"/>
<property name="employeeManager" ref="employeeMan"/>
<property name="employeeBranchManager" ref="employeeBranchMan"/>
<property name="orderItemManager" ref="orderItemMan"/>
<property name="orderFaxManager" ref="orderFaxMan"/>
<property name="sessionForm" value="true"/>
<property name="commandName" value="addTestimonialBean"/>
<property name="branchesVendorManager" ref="branchesVendorMan" />
<property name="commandClass" value="com.eam.bus.testimonial.TestimonialBean"/>
<property name="validator" ref="addTestimonialValidator"/>
<property name="formView" value="addtestimonial"/>
<property name="successView" value="listtestimonials.html"/>
</bean>
Please help me. Also let me know if you similar link where somebody has explained both the configuration in a single configuration file.
Appreciate your help.
You can very well use both XML based metadata and Annotation based configuration metadata in your application. The configuration metadata is the information how you tell the Spring container to instantiate, configure, and assemble the objects in your application. Configuration metadata is traditionally supplied in a simple and intuitive XML format. i.e XML based configuration metadata. Spring 2.5 introduced support for annotation-based configuration metadata.Starting with Spring 3.0, many features provided by the Spring JavaConfig project became part of the core Spring Framework. Thus, you have different ways of providing your configuration metadata of your application through XML, Annotation based and Java config from Spring 3.x versions. This link will take you in the right direction. You must have to learn IOC chapter in Spring documentation
you can use both annotation based configuration and xml based (ControllerClassNameHandlerMapping ) by specifying the order of these handlers.
for annotation based Configuration use below
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" >
<property name="order" value="0"/>
</bean>
for annotation based configuration we have to provide location ie: where to locate annotated controllers.
<context:component-scan base-package="ur packageName" />
here package name will be the package where #Controller classes are located.
for Controller Class Name based url Mapping
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" >
<property name= "order" value="2"/>
</bean>
I've been researching this a bunch today and I'm starting to think that what I want to do may not be possible, so I am turning to you, o mighty Stackoverflow, for help.
I'm building a RESTful services platform in Java, with Spring Data 3.1.2 + JPA as my persistence layer (as documented here). My data model objects are all implemented as interfaces that extend the Spring JpaRepository interface. I've got everything wired up and working nicely with a single datasource, as shown in this example (note that the datasource shown is Derby, but that's just for development purposes; in production, we'll be using Oracle):
<jpa:repositories base-package="com.my.cool.package.repository"/>
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
<property name="packagesToScan" value="com.my.cool.package" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
</bean>
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="url" value="jdbc:derby:derbyDB" />
<property name="username" value="dev" />
<property name="password" value="notARealPassword" />
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.DerbyTenSevenDialect" />
</bean>
The problem is that this application will need to connect to several (Oracle) databases. The credentials included with each incoming request will contain a field that tells the application which database to go to in order to fulfill that request. The schemas for each database are the same, so there's no need for separate repository interfaces for each database.
After a fair amount of Googling, it's clear that this is a common scenario. To wit:
multiple databases with Spring Data JPA
Spring + Hibernate + JPA + multiple databases
how to setup spring data jpa with multiple datasources
And here's a blog post by a (former?) Spring developer, which isn't actually relevant to the topic at hand, but someone brings it up in the comments, and the author responds with some info:
http://blog.springsource.org/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/#comment-198835
The theme that seems to be emerging is that the way to solve this problem is to define multiple EntityManagerFactories, and to wire each one to the appropriate repositories like so:
<jpa:repositories base-package="com.my.cool.package.repository1" entity-manager-factory-ref="firstEntityManagerFactory" />
<jpa:repositories base-package="com.my.cool.package.repository2" entity-manager-factory-ref="secondEntityManagerFactory" />
However, as I've mentioned, I want to reuse my repository across all of the datasources, so this approach doesn't seem like it would work.
I know that there's no way around having logic in my code that takes the relevant piece of information from the request, and uses it to determine which datasource (or EntityManagerFactory) to use. The part I'm struggling with is how to get a handle to that datasource/EntityManagerFactory and "inject" it into my repository objects. Any ideas?
If you're really using the different DataSourcees in a multi-tenant kind of way (essentially assigning a request to a DataSource and sticking with it for the entire request) you should have a look at AbstractRoutingDataSource. It essentially provides a way to keep a Map of DataSourcees as well as a callback method to return a key to be used to lookup the DataSource to be used eventually. The implementation of this method usually looks up some thread bound key and return that (or even maps that onto a DataSource map key in turn). You just have to make sure some web component binds that key to the thread in the first place.
If you have that in place your Spring configuration just sets up a bean for your sub-class of AbstractRoutingDataSource and pipes the map of DataSources into it. Your Spring Data JPA setup stays the default way. The EntityManagerFactoryBean refers to the AbstractRoutingDataSource and you have a single <jpa:repositories /> element only.
I'm new to spring and its bean injection framework and I need advice on understanding how to utilize them. Currently I have the following,
<beans>
<bean id="citationService" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
<property name="serviceUrl" value="http://localhost:8080/PPDFWeb/hello.htm"/>
<property name="serviceInterface" value="test_client.HelloService"/>
<property name="httpInvokerRequestExecutor">
<bean class="org.springframework.security.remoting.httpinvoker.AuthenticationSimpleHttpInvokerRequestExecutor">
</bean>
</property>
</bean>
</beans>
Now i need the domain name of the service url to be dynamic so I can set it somewhere programmatically in my code. Is there some way to leave the bean intact in the xml and change the serviceUrl of the bean?
Just mark it like:
<property name="serviceUrl" value="{serviceURL}"/>
Edit:
There are just too many solutions available on SO, I didn't do a good search earlier:
reading a dynamic property list into a spring managed bean
HttpInvokerProxyFactoryBean-set-url-dynamically
From what I've read so far I had the understanding that using transactions would be the solution to hibernate's lazy loading problems. The session would be available during the whole transaction in the service layer without further adue.
So maybe I misconfigured my transaction management? I'm actually a newb when it comes to spring and hibernate, but maybe you guys could help me out.
My configuration:
<bean class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
id="sessionFactory">
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
</bean>
<!-- Hibernate Template bean that will be assigned to DAOs. -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<!--
Transaction manager for a single Hibernate SessionFactory (alternative
to JTA)
-->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
My DAO implementation would simply have a #Repository annotation and a Hibernate-template bean injected using autowiring.
A typical header of a service Implementation would be:
#Service
#Transactional(readOnly=true)
public class LeerlingServiceImpl implements LeerlingService {
#Autowired
LeerlingDAO leerlingDAO;
#Autowired
LeerplanDAO leerplanDAO;
With a #Service(readOnly=false) annotation if anything is actually saved/updated in that particular method.
Do I need to configure something else to make sure that I can load the right associations in my Service, or is this normally handled by transactions?
Right now I am just a bit confused of what I should actually do, so please help me:)
Lazy-loading problems and transactions are not really related one to other. But that's another story :)
You've done all well, apart from the access to session in your beans. No sure how you are going to do this. The standard solution (in spring 2.x, not sure about 3.x, haven't looked yet) is to use HibernateDaoSupport as base class for classes were you are going to have an access to session. But personally that looks a little dodgy to me, because adds dependency on Spring-specific classes. Better way is to inject session into your beans. To do this you need to declare your session bean with definition similar to that one:
<bean name="hibernateSession" class="org.springframework.orm.hibernate3.SessionFactoryUtils" factory-method="getSession"
scope="prototype">
<constructor-arg index="0" ref="hibernateSessionFactory"/>
<constructor-arg index="1" value="false"/>
<aop:scoped-proxy/>
</bean>
and then just use it.
Here are details:
http://stas-blogspot.blogspot.com/2009/10/hibernate-spring-in-standalone.html
I think my understanding of Spring was just bad till now; there was indeed no real management for our session management. Basically what now happened was: you could get data from the DAO, but right after you received it you couldn't even get lazy collections loaded because the session was closed.
Now we are using the hibernate interceptor, which attaches the session to the thread at the beginning of each request and closes it when it ends. This is not always the most ideal solution, but for a school project I wouldn't bother too much.
The other solution seems to be: add AOP in a way that #around is used that the session is only available during a service method call. I think this is the best solution, though, I'm not going to dig that deeply right now for this project. The good thing is that I know it exists.
This article also helped me a lot: http://www.jroller.com/kbaum/entry/orm_lazy_initialization_with_dao
To those interested: here is what I had to add: In Spring MVC 3.0 there is a new feature called mvc:intereceptors which made me type less xml.
<!-- WEB-INF/applicationContext.xml or your own XML config file -->
<mvc:interceptors>
<bean
class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
</mvc:interceptors>