Recently on one forum I've found topic which released from memory my C++ days. That was topic about using "private" modifier on methods. The question there was about cases where to use it and why. Everybody knows when you are programming on C++ (as the most glaring example) one of "good practices" is "less client can do - better". Of course that's not in sense of functionality provided to client, but in mind of something which is not explicitly provided. In C++, I believe, the main reason for that is fragility of runtime, which can be easily killed if someone accidentally will do something wrong, which can also cause physical damage to person who is responsible for doing that (worth mentioning, in Java situation is slightly different, it's hard (but still possible, of course) to kill the application by "accidental coding"). And a consequence of such “good practice” is the basic rule – “make private as much as you can”.
Monday, April 5, 2010
Wednesday, March 31, 2010
Public key infrastructure
Some time ago I was asked to create presentation for my colleagues which describes Public Key Infrastructure, its components, functions, how it generally works, etc. To create that presentation, I've collected some material on that topic and it would be just dissipation to throw it out. That presentation wasn’t technical at all, and that post is not going to be technical as well. It will give just a concept, high-level picture, which, I believe, can be a good base knowledge before start looking at details.
Labels:
cryptography,
PKI
Tuesday, March 23, 2010
Mac in 1984
Was looking for some presentations on Web and found one made by Steve Jobs in 1984. The reaction of people there is just amazing, I have never seen anything similar on IT event. I wish I would visit one which will be the same impressive :)
Thursday, March 4, 2010
Redirecting or error output to variable in shell
Spent couple of painful hours trying to do that. And eventually, here is the code which will output standard output into the file and error into the variable:
bloody shell...
var=`(ls -l > ./file.txt) 2>&1`
bloody shell...
Monday, March 1, 2010
Java bridge methods explained
Bridge methods in Java are synthetic methods, which are necessary to implement some of Java language features. The best known samples are covariant return type and a case in generics when erasure of base method's arguments differs from the actual method being invoked.
Labels:
java
Tuesday, February 23, 2010
Kill all child processes from shell script
Small and simple script. Creates Ctrl-C trap and kills all it's child processes in it. Nice to have when your script has many child processes which execution have to be stopped when main script is interrupted by Ctrl-C or other signal.
kill_child_processes() {
isTopmost=$1
curPid=$2
childPids=`ps -o pid --no-headers --ppid ${curPid}`
for childPid in $childPids
do
kill_child_processes 0 $childPid
done
if [ $isTopmost -eq 0 ]; then
kill -9 $curPid 2> /dev/null
fi
}
# Ctrl-C trap. Catches INT signal
trap "kill_child_processes 1 $$; exit 0" INT
for (( i = 0 ; i <= 5; i++ ))
do
# do something...
sleep 10 &
done
wait
Monday, February 8, 2010
Exporting keys from keystore
Recently I had a similar feeling to one I had writing one of previous posts. It appeared that standard java tools do not have some basic functionality, which obviously (well, probably just for me :) ) should be there. Now I had to export key stored in keystore to share it with other department. It appeared, that keytool can't do that and you have to write tiny program by yourself. Not a big problem, really, it's even nice.
There are lots of posts in web describing how to solve that problem, and here is the best code example I found so far to solve that it.
And here is copy/paste of code snipped, just in case if original post will pass away.
If you need to send key to someone, it handy to make it base64 encoded:
There are lots of posts in web describing how to solve that problem, and here is the best code example I found so far to solve that it.
And here is copy/paste of code snipped, just in case if original post will pass away.
File keystoreFile = new File("The filename of the keystore");
KeyStore ks = KeyStore.getInstance("JKS"); // or whatever type of keystore you have
char[] pw = "the keystore password".toCharArray();
InputStream in = new FileInputStream(keystoreFile);
ks.load(in, pw);
in.close();
for (Enumerationen = ks.aliases(); en.hasMoreElements();)
{
String alias = en.nextElement();
System.out.println(" Alias\t:" + alias);
// If the key entry password is not the same a the keystore password then change this
KeyStore.Entry entry = ks.getEntry(alias, new KeyStore.PasswordProtection(pw));
if (entry instanceof KeyStore.SecretKeyEntry) {
System.out.println(" SecretKey");
KeyStore.SecretKeyEntry skEntry = (KeyStore.SecretKeyEntry) entry;
SecretKey key = skEntry.getSecretKey();
System.out.println(" alg\t: " + key.getAlgorithm());
} else if (entry instanceof KeyStore.PrivateKeyEntry) {
System.out.println(" PrivateKey");
KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) entry;
PrivateKey key = pkEntry.getPrivateKey();
System.out.println(" alg\t: " + key.getAlgorithm());
java.security.cert.Certificate certificate = pkEntry.getCertificate();
System.out.println(" Certificate type\t: " + certificate.getType());
System.out.println(" Public key\t: " + certificate.getPublicKey().getAlgorithm());
} else if (entry instanceof KeyStore.TrustedCertificateEntry) {
System.out.println(" Certificate");
KeyStore.TrustedCertificateEntry certEntry = (KeyStore.TrustedCertificateEntry) entry;
java.security.cert.Certificate certificate = certEntry.getTrustedCertificate();
System.out.println(" type\t: " + certificate.getType());
}
}
If you need to send key to someone, it handy to make it base64 encoded:
byte[] keyData = key.getEncoded();
BASE64Encoder b64Encoder = new BASE64Encoder();
String b64 = b64Encoder.encode(keyData);
System.out.println("-----BEGIN KEY-----");
System.out.println(b64);
System.out.println("-----END KEY-----");
Thursday, January 21, 2010
Compile recursively with javac
To my shame I have never used javac directly for compiling source files, always it was something like "ant". And today it was the first time on my memory when I had to do that :) It was a simple application, just an example for presentation and I didn't want to add anything additional there.
Thing which looks like a trivial task appeared to be not so trivial, because javac doesn't recursively compile files in directories, you have to specify each directory separately or create file with list of files for compilation, something like that:
find ./src -name "*.java" > sources_list.txt
javac -classpath "${CLASSPATH}" @sources_list.txt
On Windows first line should be replaced with: dir .\src\*.java /s /B > sources_list.txt
Thing which looks like a trivial task appeared to be not so trivial, because javac doesn't recursively compile files in directories, you have to specify each directory separately or create file with list of files for compilation, something like that:
find ./src -name "*.java" > sources_list.txt
javac -classpath "${CLASSPATH}" @sources_list.txt
On Windows first line should be replaced with: dir .\src\*.java /s /B > sources_list.txt
Sunday, December 20, 2009
List of Open source trading software
For everybody who is interested in topic. List of links below should help to make initial evaluation of available open-source java trading software & related products and also provides some other interesting links. Note, that projects below are not ordered in any particular order.
Groups, forums, communities
Google Group, JavaTraders
http://groups.google.com/group/JavaTraders
Elite trader, the #1 community for active traders of Stocks, Futures, Options, and Currencies.
http://www.elitetrader.com/
Trading software
Marketcetera
Open source platform for strategy-driven trading, providing you with all the tools you need for strategy automation, integrated market data, multi-destination FIX routing, broker neutrality and more.
Looks like is the leader in that list - it's well supported, has lots of capabilities and is active project.
Latest version available at 23.12.2009: 1.5.0 (released 05.2009)
http://trac.marketcetera.org/
http://www.marketcetera.com/
EclipseTrade
EclipseTrader is an application focused to the building of an online stock trading system, featuring shares pricing watch, intraday and history charts with technical analysis indicators, level II/market depth view, news watching, and integrated trading. The standard Eclipse RCP plug-ins architecture allows third-party vendors to extend the functionality of the program to include custom indicators, views or access to subscription-based data feeds and order entry.
Latest version available at 23.12.2009: 0.30.0 (released 07.2009)
http://sourceforge.net/projects/eclipsetrader/
http://eclipsetrader.sourceforge.net/
JSystemTrader
JSystemTrader is a fully automated trading system (ATS) that can trade various types of market securities during the trading day without user monitoring. All aspects of trading, such as obtaining prices, analyzing price patterns, making trading decisions, placing orders, monitoring order executions, and controlling the risk are automated according to the user preferences. The central idea behind JSystemTrader is to completely remove the emotions from trading, so that the trading system can systematically and consistently follow a predefined set of rules.
Latest version available at 23.12.2009: 6.24 (released 09.2008)
http://groups.google.com/group/jsystemtrader
ActiveQuant
AQ is a framework or an API for automated trading, opportunity detection, financial engineering, research in finance, connecting to brokers, etc. - basically everything around trading, written in Java, using Spring. All is published under a usage friendly open source license.
Latest version available at 23.12.2009: ??? Failed to find any possibility to download it or get latest version number, all links to that information are broken.
http://www.activestocks.eu/?q=node/1
http://www.activestocks.eu/
AIOTrade
AIOTrade (former Humai Trader) is a free, open source (under the terms of BSD license) stock technical analysis platform with a pluggable architecture that is ideal for extensions such as indicators and charts. It's built on pure java.
Latest version available at 23.12.2009: 1.0.3a (released 02.2007)
http://sourceforge.net/projects/humaitrader
http://blogtrader.org/
JStock
JStock makes it easy to track your stock investment. It provides well organized stock market information, to help you decide your best investment strategy.
No automated trading support.
Latest version available at 29.12.2009: 1.0.5g (released 12.2009)
http://jstock.sourceforge.net
https://sourceforge.net/projects/jstock/
Merchant of Venice
Venice is a stock market trading programme that supports portfolio management, charting, technical analysis, paper trading and experimental methods like genetic programming. Venice runs in a graphical user interface with online help and has full documentation.
Latest version available at 23.12.2009: 0.7b (released 04.2006)
http://sourceforge.net/projects/mov
http://mov.sourceforge.net/
Market Analysis System
The Market Analysis System (MAS) is an open-source software application that provides tools for analysis of financial markets using technical analysis. MAS provides facilities for stock charting and futures charting, including price, volume, and a wide range of technical analysis indicators. MAS also allows automated processing of market data — applying technical analysis indicators with user-selected criteria to market data to automatically generate trading signals — and can be used as the main component of a sophisticated trading system.
Latest version available at 23.12.2009: 1.6.6 (released 07.2004)
http://sourceforge.net/projects/eiffel-mas
http://eiffel-mas.sourceforge.net/
Open Java Trading System
The Open Java Trading System (OJTS) is meant to be a common infrastructure to develop stock trading systems. The project's aim is to provide a self contained pure Java (platform independent) common infrastructure for developers of trading systems.
Latest version available at 23.12.2009: 0.13 (released 06.2005)
http://sourceforge.net/projects/ojts/
http://ojts.sourceforge.net/
Oropuro trading system
The software perform the technical analysis of stock or commodity for various markets, manage portfolio definitions and orders. It has the base characteristics of most populars technical analysis software.
The most of information about that project is in Italian language, so it's really hard to dive in it :(
Latest version available at 23.12.2009: 0.2.4 (released 11.2007)
http://sourceforge.net/projects/oropuro
http://www.oropuro.org
TrueTrade
TrueTrade is a framework for developing, testing and running automatic trading systems. It is intended to provide support for a wide range of orders, financial instruments and time scales. It provides tooling for backtesting the strategy against historical data, and a separate tool for running the strategies in live mode.
Latest version available at 23.12.2009: 0.5 (released 05.2007)
http://code.google.com/p/truetrade/
http://groups.google.com/group/TrueTrade-Gen
http://groups.google.com/group/TrueTrade-Dev
(j)robotrader
Robotrader is a simulation platform for automated stock exchange trading. It delivers statistics to analyse performance on historic data and allows comparison between trading strategies.
Latest version available at 23.12.2009: 0.2.7 (released 02.2006)
http://jrobotrader.atspace.com
http://sourceforge.net/projects/robotrader/
SFL Java Trading System Enviroment
At current moment project is inactive. Author suggests to use ActiveQuant instead.
http://sourceforge.net/projects/sfljtse
http://www.sflweb.org/index.php?blog=sfljtse
Related software
TA-Lib: Technical Analysis Library
TA-Lib is widely used by trading software developers requiring to perform technical analysis of financial market data.
* Includes 200 indicators such as ADX, MACD, RSI, Stochastic, Bollinger Bands etc...
* Candlestick pattern recognition
* Open-source API for C/C++, Java, Perl, Python and 100% Managed .NET
Latest version available at 23.12.2009: 0.4 (released 09.2007)
http://ta-lib.org/index.html
Tail - A java technical analysis lib
Technical Analysis studies forecasting future price trends with the objective of managea best moment to buy and sell shares. The Tail's target is to develop a Java Open-Source library that abstracts the basic components of Technical Analysis, supplying tools for creation, manipulation and evaluation of strategies to buy and sell.
Latest version available at 15.01.2010: 1.0 (released 12.2007)
http://tail.sourceforge.net/
JessX
JessX Project's main goal is to create a program allowing for the simulation of a financial market with realistic features (such as an order book and realistic orders). Researchers and teachers in Finance may find it helpful in their works.
Latest version available at 23.12.2009: 1.5 (released 05.2008)
http://jessx.ec-lille.fr/
QuickFIX/J
100% Java Open Source FIX (Financial Information eXchange protocol) Engine
Latest version available at 23.12.2009: 1.4 (released 02.2009)
http://www.quickfixj.org/
Auge
Auge is an easy-to-use and very simple financial portfolio management application. Auge will help you monitor and analyze your stock and mutual fund positions, providing powerful insight into your entire investment portfolio.
Latest version available at 23.12.2009: 0.2 (released 04.2007)
http://sourceforge.net/projects/auge
http://auge.sourceforge.net/
Matrex
Advanced spreadsheet.
Latest version available at 23.12.2009: 1.3.8 (released 10.2009)
http://sourceforge.net/projects/matrex/
http://matrex.sourceforge.net/
Data Visualizer
Data Visualizer displays text file stock market type data ("Date,Open,High,Low,Close,Volume,Adjusted Close Price") as Stock Charts, featuring a variation of Japanese "Candlesticks" chart elements.
Latest version available at 23.12.2009: 0.0.1 (released 03.2006)
http://sourceforge.net/projects/dataviews
http://dataviews.sourceforge.net/
Groups, forums, communities
Google Group, JavaTraders
http://groups.google.com/group/JavaTraders
Elite trader, the #1 community for active traders of Stocks, Futures, Options, and Currencies.
http://www.elitetrader.com/
Trading software
Marketcetera
Open source platform for strategy-driven trading, providing you with all the tools you need for strategy automation, integrated market data, multi-destination FIX routing, broker neutrality and more.
Looks like is the leader in that list - it's well supported, has lots of capabilities and is active project.
Latest version available at 23.12.2009: 1.5.0 (released 05.2009)
http://trac.marketcetera.org/
http://www.marketcetera.com/
EclipseTrade
EclipseTrader is an application focused to the building of an online stock trading system, featuring shares pricing watch, intraday and history charts with technical analysis indicators, level II/market depth view, news watching, and integrated trading. The standard Eclipse RCP plug-ins architecture allows third-party vendors to extend the functionality of the program to include custom indicators, views or access to subscription-based data feeds and order entry.
Latest version available at 23.12.2009: 0.30.0 (released 07.2009)
http://sourceforge.net/projects/eclipsetrader/
http://eclipsetrader.sourceforge.net/
JSystemTrader
JSystemTrader is a fully automated trading system (ATS) that can trade various types of market securities during the trading day without user monitoring. All aspects of trading, such as obtaining prices, analyzing price patterns, making trading decisions, placing orders, monitoring order executions, and controlling the risk are automated according to the user preferences. The central idea behind JSystemTrader is to completely remove the emotions from trading, so that the trading system can systematically and consistently follow a predefined set of rules.
Latest version available at 23.12.2009: 6.24 (released 09.2008)
http://groups.google.com/group/jsystemtrader
ActiveQuant
AQ is a framework or an API for automated trading, opportunity detection, financial engineering, research in finance, connecting to brokers, etc. - basically everything around trading, written in Java, using Spring. All is published under a usage friendly open source license.
Latest version available at 23.12.2009: ??? Failed to find any possibility to download it or get latest version number, all links to that information are broken.
http://www.activestocks.eu/?q=node/1
http://www.activestocks.eu/
AIOTrade
AIOTrade (former Humai Trader) is a free, open source (under the terms of BSD license) stock technical analysis platform with a pluggable architecture that is ideal for extensions such as indicators and charts. It's built on pure java.
Latest version available at 23.12.2009: 1.0.3a (released 02.2007)
http://sourceforge.net/projects/humaitrader
http://blogtrader.org/
JStock
JStock makes it easy to track your stock investment. It provides well organized stock market information, to help you decide your best investment strategy.
No automated trading support.
Latest version available at 29.12.2009: 1.0.5g (released 12.2009)
http://jstock.sourceforge.net
https://sourceforge.net/projects/jstock/
Merchant of Venice
Venice is a stock market trading programme that supports portfolio management, charting, technical analysis, paper trading and experimental methods like genetic programming. Venice runs in a graphical user interface with online help and has full documentation.
Latest version available at 23.12.2009: 0.7b (released 04.2006)
http://sourceforge.net/projects/mov
http://mov.sourceforge.net/
Market Analysis System
The Market Analysis System (MAS) is an open-source software application that provides tools for analysis of financial markets using technical analysis. MAS provides facilities for stock charting and futures charting, including price, volume, and a wide range of technical analysis indicators. MAS also allows automated processing of market data — applying technical analysis indicators with user-selected criteria to market data to automatically generate trading signals — and can be used as the main component of a sophisticated trading system.
Latest version available at 23.12.2009: 1.6.6 (released 07.2004)
http://sourceforge.net/projects/eiffel-mas
http://eiffel-mas.sourceforge.net/
Open Java Trading System
The Open Java Trading System (OJTS) is meant to be a common infrastructure to develop stock trading systems. The project's aim is to provide a self contained pure Java (platform independent) common infrastructure for developers of trading systems.
Latest version available at 23.12.2009: 0.13 (released 06.2005)
http://sourceforge.net/projects/ojts/
http://ojts.sourceforge.net/
Oropuro trading system
The software perform the technical analysis of stock or commodity for various markets, manage portfolio definitions and orders. It has the base characteristics of most populars technical analysis software.
The most of information about that project is in Italian language, so it's really hard to dive in it :(
Latest version available at 23.12.2009: 0.2.4 (released 11.2007)
http://sourceforge.net/projects/oropuro
http://www.oropuro.org
TrueTrade
TrueTrade is a framework for developing, testing and running automatic trading systems. It is intended to provide support for a wide range of orders, financial instruments and time scales. It provides tooling for backtesting the strategy against historical data, and a separate tool for running the strategies in live mode.
Latest version available at 23.12.2009: 0.5 (released 05.2007)
http://code.google.com/p/truetrade/
http://groups.google.com/group/TrueTrade-Gen
http://groups.google.com/group/TrueTrade-Dev
(j)robotrader
Robotrader is a simulation platform for automated stock exchange trading. It delivers statistics to analyse performance on historic data and allows comparison between trading strategies.
Latest version available at 23.12.2009: 0.2.7 (released 02.2006)
http://jrobotrader.atspace.com
http://sourceforge.net/projects/robotrader/
SFL Java Trading System Enviroment
At current moment project is inactive. Author suggests to use ActiveQuant instead.
http://sourceforge.net/projects/sfljtse
http://www.sflweb.org/index.php?blog=sfljtse
Related software
TA-Lib: Technical Analysis Library
TA-Lib is widely used by trading software developers requiring to perform technical analysis of financial market data.
* Includes 200 indicators such as ADX, MACD, RSI, Stochastic, Bollinger Bands etc...
* Candlestick pattern recognition
* Open-source API for C/C++, Java, Perl, Python and 100% Managed .NET
Latest version available at 23.12.2009: 0.4 (released 09.2007)
http://ta-lib.org/index.html
Tail - A java technical analysis lib
Technical Analysis studies forecasting future price trends with the objective of managea best moment to buy and sell shares. The Tail's target is to develop a Java Open-Source library that abstracts the basic components of Technical Analysis, supplying tools for creation, manipulation and evaluation of strategies to buy and sell.
Latest version available at 15.01.2010: 1.0 (released 12.2007)
http://tail.sourceforge.net/
JessX
JessX Project's main goal is to create a program allowing for the simulation of a financial market with realistic features (such as an order book and realistic orders). Researchers and teachers in Finance may find it helpful in their works.
Latest version available at 23.12.2009: 1.5 (released 05.2008)
http://jessx.ec-lille.fr/
QuickFIX/J
100% Java Open Source FIX (Financial Information eXchange protocol) Engine
Latest version available at 23.12.2009: 1.4 (released 02.2009)
http://www.quickfixj.org/
Auge
Auge is an easy-to-use and very simple financial portfolio management application. Auge will help you monitor and analyze your stock and mutual fund positions, providing powerful insight into your entire investment portfolio.
Latest version available at 23.12.2009: 0.2 (released 04.2007)
http://sourceforge.net/projects/auge
http://auge.sourceforge.net/
Matrex
Advanced spreadsheet.
Latest version available at 23.12.2009: 1.3.8 (released 10.2009)
http://sourceforge.net/projects/matrex/
http://matrex.sourceforge.net/
Data Visualizer
Data Visualizer displays text file stock market type data ("Date,Open,High,Low,Close,Volume,Adjusted Close Price") as Stock Charts, featuring a variation of Japanese "Candlesticks" chart elements.
Latest version available at 23.12.2009: 0.0.1 (released 03.2006)
http://sourceforge.net/projects/dataviews
http://dataviews.sourceforge.net/
Forex Optimizer
Absolutely new revolutionary trade platform, is intended both for beginners, and for the tempered traders of Forex. Beginners can study market Forex, using a simulator, not risking the capitals and not being connected to the Internet. For more skilled traders Forex Optimizer allows to create and optimize trade strategy, not having knowledge in programming to operate (to make trading operations) the real account of the broker. The platform can offer professionals greater functionality for application of the strategy and methods of trade in market Forex.
Latest version available at 08.12.2010: 2.7 (released ??)
http://www.gordago.com/opensource/forex-optimizer/
Absolutely new revolutionary trade platform, is intended both for beginners, and for the tempered traders of Forex. Beginners can study market Forex, using a simulator, not risking the capitals and not being connected to the Internet. For more skilled traders Forex Optimizer allows to create and optimize trade strategy, not having knowledge in programming to operate (to make trading operations) the real account of the broker. The platform can offer professionals greater functionality for application of the strategy and methods of trade in market Forex.
Latest version available at 08.12.2010: 2.7 (released ??)
http://www.gordago.com/opensource/forex-optimizer/
Labels:
java,
opensource,
trading
Wednesday, October 21, 2009
Hibernate + Spring in Standalone application
Just a quick reminder howto use Hibernate + Spring in standalone application.
First comes hibernate session factory. I prefer to use separate file for hibernate, Instead of configuring it Spring's applicationContext.xml:
Transaction manager:
Next is hibernate session. Hibernate guys suggest to use HibernateDaoSupport class as base for your DAOs, but to be completely honest, I'm not really comfortable with it, because it adds really weird dependency on Spring in DAO classes. Instead, it looks more natural to use dependency injection, which is really Spring's approach. To archive that all you need to do is mark session definition as being scoped proxy, set scope to 'prototype' and define SessionFactoryUtils#getSession as factory method. In result, each call to "any_method" in hibernate session bean instance is converted to SessionFactoryUtils.getSession().any_method():
And all together:
In DAO class there is no need to worry about session management, "tx:annotation-driven" will do all work for you. The only thing, which developer has to think about is appropriate usage of transaction annotations.
First comes hibernate session factory. I prefer to use separate file for hibernate, Instead of configuring it Spring's applicationContext.xml:
<bean name="hibernateSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="configLocation" value="hibernate.cfg.xml"/>
<!-- Those package will be scanned for classes with persistence annotations -->
<property name="packagesToScan" value="net.test.domain"/>
<!-- Annotated package. Contains package-level configuration. -->
<property name="annotatedPackages" value="net.test.domain"/>
</bean>
Transaction manager:
<bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="hibernate.session.factory"/>
</bean>
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
Next is hibernate session. Hibernate guys suggest to use HibernateDaoSupport class as base for your DAOs, but to be completely honest, I'm not really comfortable with it, because it adds really weird dependency on Spring in DAO classes. Instead, it looks more natural to use dependency injection, which is really Spring's approach. To archive that all you need to do is mark session definition as being scoped proxy, set scope to 'prototype' and define SessionFactoryUtils#getSession as factory method. In result, each call to "any_method" in hibernate session bean instance is converted to SessionFactoryUtils.getSession().any_method():
<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 all together:
<?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:tx="http://www.springframework.org/schema/tx"
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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean name="hibernateSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="configLocation" value="hibernate.cfg.xml"/>
<!-- Those package will be scanned for classes with persistence annotations ->
<property name="packagesToScan" value="net.test.domain"/>
<!-- Annotated package. Contains package-level configuration. -->
<property name="annotatedPackages" value="net.test.domain"/>
</bean>
<bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="hibernateSessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<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>
<bean name="someDao" scope="singleton" class="net.test.TestDAO">
<property name="session" ref="hibernateSession"/>
</bean>
</beans>
In DAO class there is no need to worry about session management, "tx:annotation-driven" will do all work for you. The only thing, which developer has to think about is appropriate usage of transaction annotations.
Subscribe to:
Posts (Atom)