|
|
用户名:homk 笔名:homk 地区: 四川-成都 行业:其他 |
| 日 | 一 | 二 | 三 | 四 | 五 | 六 |
生活本就是最真实的剧本,我们都各自演着自己的角色,有时是真情流露有时却是情非得已。我们应该溶入这个世界,放飞自己的理想!
名字测试
| |||||||||||||||||||||||||||
暴笑
一个好玩的东东
好象速度快了许多
今天在我google个人门户,里面看到bokee.顺便看了一下我的blog好象现在速度快了许多。我还是用的教育网哦。以前的速度真的是不敢恭维。目前在用msn space 主要在那边写blog 。有些东西也写在google group里面。这几天喜欢在gmail 里面聊天。觉得哪个挺有创意的。gmail现在的功能也比以前强多了。通讯录也做了升级终于等到今天了。以前邮件列表太多太乱了。现在好了可以分组管理了。
一直想找一个比较稳定,速度快一点的blog用。目前好象还没有。知道的朋友推荐一个吧。我的
msn space http://space.msn.com/gallon6好象是这个。记不大清楚了。左边列表里面有。马上过大年了。大家新年好哟~~~~
这几天遇到了好多怪问题
好久没有来这里了
确实有一段时间没有来这里了,前段时间在MSN上面写blog.当总觉得哪个经常出问题。虽然这里速度慢了一点。还是算不错了。以后还是回来继续坚持阵地,呵呵。
也许一切都是天意吧,最终走了一圈,又走回来了。正如我的择业与创业样。与世隔绝默默学习了接近半年时间。现在总算又回来了。但是我好象发现现在有点落伍了哦。基础到是起来了,最新的潮流和一些思维好象有待更新了。总算这个社会发展的挺快的。星座上说今年是天蝎事业辉煌的一年。我就当他是真的吧。其实我从小到现在都有一个想法就是,我也要想***一样有自己的事业。我一个朋友说我们天蝎总是不达目的不罢休?难道我现在真的相信星座了?也许吧。
最近学习计划
复习和学习一些知识
1、复习C(done)
2、复习C++(doing)
3、<<c++ primer
4、<<STL分析>>
4、<<数据结构c/c++>>
5、<<设计模式>>c++实现
6、eMule代码分析
7、unix c/c++
时间安排:每天上午1个小时,下午一个小时,晚上2个小时
时间:10月12日-11月12日
>>>挑战自我、挑战时间、挑战世界<<<
今天看了几篇文章后的一些感受,希望在以后对自己有帮助
今天我现在终于明白为什么有那么多的朋友象上名牌大学了,包括我在内.以前还没有真正明白这个,究竟是什么目的.也许是最近马上要毕业了大家都在找工作吧.虽然我早已经找到工作,但还是时常看一些招聘的信息.好像在中国的企业对学历和学校比较敏感.外企业不怎么了解,外企对英语应该要求比较高.以前听说外企只看中能力,不看中学历.这个不 知道是真的还是假的.但有一点是值得肯定的:一流大学的学习风气,学习份围,师资力量以及整体学生的自觉性也许都要高点.为什么现在的企业都喜欢名校的学生呢?是不是他们的能力真的是那么好呢?我个人的愚见,他们中有能力强的,当然也有不是那么出色,大学混时间的.但他们的基础整体上应该是比较好的,即使马上重头学习一种新的知识问题应该不大.也学正是这样,许多大公司喜欢自己培养.对于哪些小公司最希望你一去就能参加到实际的工作中去.最近看到许多公司在招聘是还是那么看中学校和学历.不禁觉得有点心寒.看来我是真的落后了.
回来想想,是乎我现在还存在很多问题.需要学习的东西还有很多.以前有些基础知识学习得不够好,有时自己感觉得出来,是不是时候该补一下了呢,我看这个还是很有必要的.经过这接近一年的工作和学习,我发现了我的薄弱点,我把近期目标定为--->软件设计师--->系统分析师,同时坚持管理方面的知识积累.也许正是我把近期目标定为系统分析员,暴露了还缺少的能力或者薄弱的地方.其实这只是一个称号而已,主要还是在提升能力.
现在落后了不要紧,慢慢赶上.
恒心,信心,创新,
着了今天晚上要考<>
看书眼睛都看花了
今天晚上一口起看了一本353页的,英文电子书籍.写的挺不错的.可惜作者只出了电子版没有印刷成书籍.不过也好看电子版的还不用给钱.呵呵~~~ 不过现在都看英文原版书了,国人写的书或者翻译的书都不行,要不就是这里COPY一点那里COPY一点没有有点原创的,这有什么意思.况且很多翻出来就变了味道.国外的书国内一般嘴快要一年后才能出来.这就是差距.......所以认识E文的朋友,最好看原版的书.呵呵~~~
TestNG: The next generation of unit testing
Summary
Everyone knows JUnit, the Java unit-testing framework. JUnit has some annoying specificities that make it unsuitable for complex unit testing involving grouping, asynchronous, and parallel testing. This article introduces TestNG, an alternative testing framework targeted at J2SE 5.0. (1,900 words; April 4, 2005)Page 1 of 2
Advertisement
estNG, written by Cedric Beust and Alexandru Popescu, is a light framework based on Java annotations (for J2SE 5.0) that allows you to design complex unit testing for J2SE 5.0 and J2SE 1.4. Why bother learning another unit-testing framework when you're already comfortable using JUnit? If you are interested in simplifying your unit-test cases, in leveraging J2SE 5.0 annotations to tag your test classes as well as being backward compatible with J2SE 1.4, in having out-of-the-box support for dependent methods and parallel and asynchronous testing, TestNG is the tool you are looking for.
This article starts with a description of the JUnit annoyances and introduces TestNG through numerous examples. A case study shows how to use TestNG for asynchronous testing.
JUnit annoyances
The JUnit testing framework has been around for a long time and is (hopefully) widely used by Java developers to unit test developed software. However, the framework has some annoying specificities, which the following sections describe.Multiple instantiations per TestCase
MultipleTestCaseinstantiations is a well-known issue. Thesetup()andteardown()methods are called before and after each test method; moreover, the test class that must extendTestCaseis also instantiated each time a test method is called. Although multipleTestCaseinstantiations might prove acceptable for simple test cases, what if you want to set up an object that is to be reused across more than one test method, for example, a Java Database Connectivity connection (or, for that matter, a Java Naming and Directory Interface (JNDI) context)?
PainOneTest.javaillustrates the problem:
public class PainOneTest extends TestCase {
/**
* PainOneTest
*/
public PainOneTest() {
System.out.println("PainOneTest");
}
/**
* @see TestCase#setUp()
*/
protected void setUp() throws Exception {
System.out.println("setUp()");
}
/**
* @see TestCase#tearDown()
*/
protected void tearDown() throws Exception {
System.out.println("tearDown()");
}
/**
* testMe
*/
public void testMe() {
System.out.println("testMe");
}
/**
* testYou
*/
public void testYou() {
System.out.println(&qut;testYou");
}
}This code produces the following output:
PainOneTest
PainOneTest
setUp()
testMe
tearDown()
setUp()
testYou
tearDown()The
TestSetupclass circumvents this issue, as illustrated below:
public class PainTwoTest extends TestCase {
/**
* Test
* @return
*/
public static Test suite() {
return new TestSetup(new TestSuite(PainTwoTest.class)) {
public void setUp() throws Exception {
System.out.println("setUp()");
}
public void tearDown() throws Exception {
System.out.println("tearDown()");
}
};
}
/**
* PainOneTest
*/
public PainTwoTest() {
System.out.println("PainOneTest");
}
/**
* testMe
*/
public void testMe() {
System.out.println("testMe");
}
/**
* testYou
*/
public void testYou() {
System.out.println("testYou");
}
/**
* main
* @param _
*/
public static void main(String []_) {
Test test = PainTwoTest.suite();
}
}This code produces:
PainOneTest
PainOneTest
setUp()
testMe
testYou
tearDown()The above solution introduces a
staticmethod, and all variables accessed by it must also be declaredstatic. Although I have nothing in particular againststaticmethods, you must take care when implementing test methods for concurrency access (sharingstaticobjects) andstaticinitialization (occurring only once per VM).Remember, when using Ant, the default behavior is to use the VM that started Ant to execute all the tasks; in the above scenario, you may well have to use the
forkattribute of the Java core task.Furthermore, multiple instantiations of the
TestCaseclass remain. Surely, if we want the test methods to be independent of each other, we would place them into differentTestCaseclasses. So why multiple instantiations? Multiple instantiations allow you to isolate independent methods within the sameTestCaseclass, which is not always the desired behavior. Finally, too much technical code is required for circumventing the multiple-instantiations scenario: I just want a test POJO (plain old Java object) class.How does TestNG handle multiple instantiations?
TestNG does not require static block initialization and has a flexible configuration scheme for handling test classes based on regular expressions and XML configuration files. TestNG does not instantiate the test class several times.Multithreaded support
GroboUtils is an addition to JUnit that supports multithreaded unit tests (since the JUnit framework lacks such support). N. Alex Rupp gives an overview of GroboUtils in "Multithreaded Tests with JUnit" (java.net, August 2003). Although very useful, GroboUtils is not to my taste as it requires too much glue code to handle multithreaded unit tests.How does TestNG handle multithreaded unit tests?
TestNG has multithreaded and parallel unit tests built in its core. You don't need to write specific code to handle multithreaded unit tests as they are just a configuration of TestNG.Why should I extend a specific class and prefix the methods with test?
I would rather tag any method than be obliged to prefix methods withtest, a task that JUnit requires. Admittedly, this is a minor point, but all IDEs now give you a view (like the Eclipse outline view) that helps you quickly browse your methods to find the one you want—that is, if they are not all prefixed with the same four letters. From a practical viewpoint, the Eclipse outline view is useless when you have dozens of test methods on a class that start with the same four letters.How does TestNG handle test method names?
TestNG uses Java annotations as specified by Java Specification Request 175 to tag methods for testing and grouping, and for expected exceptions, and so on.Introducing TestNG
TestNG is inspired by JUnit and also NUnit a unit-testing framework for .Net.TestNG introduces new functionalities to unit testing such as:
- Support for Java annotations (if unfamiliar with annotations, see sidebar "What Are Annotations")
- XML configuration file for test configuration
- No required class extension or interface implementation
- Support for dependent methods and groups
- Support for parallel testing
- Parameters for test methods
- Arbitrary number of invocations plus success rate
Step by step: Your first TestNG program
Let's get started with TestNG. The remaining sections of this article introduce you to the TestNG features, starting with a basic first unit test: how to configure it and run it.Here is a simple test class:
package org.jyperion.testng;
import com.beust.testng.annotations.*;
public class FirstTest {
@Configuration(beforeTestClass = true)
public void configure() {
System.out.println("configure");
}
@Test(groups = {"exec-group"})
public void exec() {
System.out.println("exec");
assert 1 == 2;
}
}Note that no interface or class is required for your test class. The
@Configurationannotation is the equivalent of the JUnit methodsetup(); you can annotate any method in your test class.@Configuration(beforeTestClass = true)means that the annotated method will be called just once before testing any method in the class. The@Testannotation is equivalent to the JUnit methods prefixed with the wrdtest.Next comes the XML configuration test called
testng.xml:
Finally, TestNG's invocation:
java –ea com.beust.testng.TestNG testng.xmlNote:
-eaenables assertions.The following appears on the console:
configure
exec
[TestRunner] FAILED: org.jyperion.testng.FirstTest.exec
[TestRunner] REASON: java.lang.AssertionError
===============================================
TestNG Samples
Total tests run: 1, Failures: 1 Skips: 0
===============================================An HTML report is also created in a folder called test-output:
Figure 1. Your first TestNG HTML report. Click on thumbnail to view full-sized image.
An interesting feature of TestNG is the test setup mechanism enabled by using the
@Configurationannotation in four different scenarios:
- Run configuration method once before all tests
- Run configuration method once before every test
- Run configuration method once after every test
- Run configuration method once after all tests
Moreover, if you use TestNG's powerful grouping feature (described in subsequent sections), the
@Configurationmethods can have a determined execution order.TestNG DTD view
The configuration is defined by a DTD (document type definition). Figure 2 shows the schematic view.
Figure 2. TestNG DTD. Click on thumbnail to view full-sized image.
The test annotation
The@Testannotation is defined as:
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({java.lang.annotation.ElementType.METHOD,
java.lang.annotation.ElementType.TYPE})
public @interface Test {
public String[] groups() default {};
public boolean enabled() default true;
public String[] parameters() default {};
public String[] dependsOnGroups() default {};
public long timeOut() default 0;
}The
groupselement allows you to group methods and groups. By configuringtestng.xml, you can include or exclude groups using regular expressions:
public class GroupTest {
@Test(groups = {"group-one"})
public void init() {
System.out.println("init#group-one");
}
@Test(groups = {"group-two"}, dependsOnGroups = {"group-one"})
public void exec() {
System.out.println("exec#group-two");
}
@Test(groups = {"group-three"})
public void testMe() {
System.out.println("testMe#group-three");
}
}The corresponding
testng.xml:
Parameters
Parameters defined intestng.xmlcan be passed to the test methods at runtime:
public class ParameterTest {
@Test(parameters = { "jndi-name" })
public void lookup(String jndiName) {
System.out.println("lookup("+jndiName+")");
}
}The corresponding
testng.xml:
Note that parameters can be placed within the
suiteelement, within thetestelement, or within theclasselement, so that your parameter is available to all the classes in the suite, to all the classes in the test, or to only the class.The corresponding
testng.xml:
verbose="1"
parallel="true"
thread-count="10">
The element
parallelis set totrueto instruct TestNG to run the tests in parallel.thread-countspecifies the number of threads in the pool (if omitted, default is5).TheHTML report in Figure 3 shows that the methods run chronologically and also presents the thread identifier used to execute a test method.
Figure 3. TestNG parallel report. Click on thumbnail to view full-sized image.
Figure 4 shows the threads associated with the test methods.
Figure 4. TestNG parallel report with thread information. Click on thumbnail to view full-sized image.
TestNG allows two running scenarios:
- Sequential run of tests (default)
- Parallel run of tests
To select which scenario to use, simply edit the
testng.xml.Another nice feature of TestNG is its support of
timeouts, which can be used in parallel and nonparallel modes using thetimeOutattribute in@Test.Ant task
TestNG is also shipped with an Ant task:
fork="yes"
classpath="${my.classpath}"
outputDir = "${basedir}/test-output">
Using this Ant task (which is part of the TestNG distribution), TestNG could be used for continuous integration, for example.
Support for J2SE 1.4
TestNG supports old-style javadoc-like tags for J2SE 1.4. I do not bother describing them here because they are not of much interest if you are testing J2SE 5.0 software. However, TestNG can be used for testing J2SE 1.4 applications.Extending TestNG
TestNG is available under the Apache Software License, and, as an open source project, can be extended to enable further development. The TestNG distribution comes with the source, and, in this section, I outline a way to register a listener that listens to events when TestNG executes tests. This approach resembles a SAX (Simple API for XML) implementation in that you are notified while TestNG runs the tests. I illustrate how to extend TestNG by implementing a PDF report generator using the fantastic iText library, released under MPL and LGPL.Note: Cedric Beust is currently designing a flexible plug-in framework that will allow developers to extend TestNG beyond JUnit's abilities.
To extend TestNG to generate a PDF report, you (currently) need to:
- Write a class that implements the
com.beust.testng.ITestListenerinterface- Register that class in the
initLoggers()method from thecom.beust.testng.TestRunnerclass- Rebuild the TestNG JAR
You can find the code for the PDF generator in the JyperionListener.java file; to see the result, open the JypTest.pdf file (both files are downloadable from Resources).
Case study: Price publishing and asynchronous testing
In this simple case study, we simulate sending prices to an electronic communications network (ECN) market (implemented by a Remote Method Invocation server) from a client using Java Message Service (JORAM—Java Open Reliable Asynchronous Messaging—from ObjectWeb is used as message-oriented middleware). This study illustrates how to use TestNG for testing asynchronous code (for more on the topic, read the Testing Asynchronous Code Weblog). Our ECN simulator sends the same price back to the client 90 percent of the time, acknowledging the market's price. It sends a slightly different bid and ask price 5 percent of the time and an "off" status for that quote another 5 percent of the time. The price publisher is a Java client that publishes messages using Java Message Service (JMS).The
TestPricePublisheris just another JMS client that usesPricePublisherto send prices and then waits for a price to return (usingwait(long)so a long delay can causeLongUpdateException). TheTestPricePublisheralso checks if the price received is identical to the one sent (if not, aWrongPriceExceptionis thrown) and if the price status is on (if not, anOffExceptionis thrown).The code for asynchronous testing (from
TestPricePublisher) follows below:
@Test(invocationCount = 20)
public void sendPrice() throws LongUpdateException, WrongPriceException, OffException, InterruptedException {
this.sendPrice("JYPERION", this.askPrice, this.bidPrice);
this.askPrice += 0.01;
this.bidPrice += 0.01;
synchronized (this) {
try {
long TIMEOUT = 100;
this.wait(TIMEOUT);
if (this.quote == null)
throw new LongUpdateException("No message received");
if (quote.getStatus() == PriceStatus.OFF)
throw new OffException("Quote " + this.quote.getISIN() + " is OFF");
if (!quote.isPriceConsistent())
throw new WrongPriceException("Wrong price for " + this.quote.getISIN());
} catch (InterruptedException e) {
throw new InterruptedException();
} finally {
this.quote = null;
}
}
}
/**
* @see javax.jms.MessageListener#onMessage(javax.jms.Message)
*/
public void onMessage(Message msg) {
try {
synchronized(this) {
this.quote = (Quote) ((ObjectMessage)msg).getObject();
LOGGER.info("Notifying waiting threads");
this.notifyAll();
}
} catch (JMSException e) {
e.printStackTrace();
&nbp; }
}The corresponding
testng.xml:
parallel="true"
thread-count="10"
verbose="1">
The generated HTML report:
Figure 5. TestNG report for the price publisher. Click on thumbnail to view full-sized image.
If you run the tests more than once, TestNG keeps them in the generated HTML page.
What is next?
Cedric and Alexandru are currently working on:
- A pluggable module architecture for TestNG (so you can plug in your PDF generation engine in a standard way)
- An Eclipse plug-in for TestNG, see a preview in Figure 6
Figure 6. Eclipse plug-in preview. Click on thumbnail to view full-sized image.
Conclusion
This article described how to employ some new features for unit testing with TestNG. Among TestNG's capabilities, I would qualify its support for J2SE 5.0 annotations, flexible test configurations based on XML files and regular expressions, support for dependent test methods, and core multithreaded support as being the most important. TestNG shows that there is still room for improvement in unit testing. I am certain developers would find refreshing ideas in TestNG.One last thing, if TestNG is lacking a feature, you can argue your case in TestNG users' mailing list. If Cedric and Alexandru are convinced, most likely, this feature will be added to the next release. Could you be more agile?
Implementing Transaction Suspension in Spring
The Spring Framework, a popular Java/J2EE application framework built on a lightweight Inversion-of-Control container, is particularly well-known for its data access and transaction management capabilities. Spring's declarative transaction demarcation can be applied to any POJO target object, with the full sophistication of declarative transactions as found in EJB Container-Managed Transactions (CMT). The choices for a back-end transaction manager range from simple JDBC-based transactions to full-fledged J2EE transactions via JTA.
This article discusses Spring's transaction management facilities in detail. The focus is on leveraging Spring's declarative transactions for POJOs, with JTA as the back-end transaction strategy. The article shows that Spring's transaction services can seamlessly interact with a J2EE server's transaction coordinator, for example the transaction coordinator for BEA WebLogic Server, essentially serving as an alternative to the traditional transaction demarcation style of EJB CMT.
As an illustration of Spring's declarative transaction demarcation style, let's look at the configuration for the central service facade of Spring's PetClinic sample application:
java:comp/env/jdbc/petclinic PROPAGATION_REQUIRED,readOnly PROPAGATION_REQUIRED
This follows Spring's standard XMLBean definition format. It defines:
Note: As an alternative to explicit proxy definitions, Spring also supports an auto-proxying mechanism and the use of source-level metadata either through Commons Attributes or through J2SE 5.0 annotations. A discussion of these aternatives is beyond the scope of this article; refer to the Spring documentation for details.
The service interface and service implementation used are specific to the application and can be implemented without any awareness of Spring or Spring transaction management in particular. Plain Java objects can serve as the target objects, and any plain Java interface can serve as the service interface. Here is an example of the Clinic interface:
public interface Clinic {
Pet loadPet(int id);
void storePet(Pet pet);
...
}
A simple implementation of this interface is shown below, assuming that it uses JDBC for performing the necessary data access. It receives the JDBC DataSource via a bean property setter; this corresponds directly to the dataSource property definition in the configuration above.
public class JdbcClinic implements Clinic {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Pet loadPet(int id) {
try {
Connection con = this.dataSource.getConnection();
...
}
catch (SQLException ex) {
...
}
}
public void storePet(Pet pet) {
try {
Connection con = this.dataSource.getConnection();
...
}
catch (SQLException ex) {
...
}
}
...
}
As you can see, the code is straightforward. We are using a simple Java object. The transaction management is handled by the transactional proxy, which we examine next.
Note that the actual JDBC-based Clinic implementations in the PetClinic sample application leverage Spring's JDBC support classes to avoid working at the plain JDBC API level. However, Spring's transaction management also will work with a plain JDBC-based implementation, such as the one illustrated above.
In addition to the JdbcClinic instance, the configuration also defines a transactional proxy for it. The actual interfaces exposed by this proxy can be specified explicitly, if desired. By default, all interfaces implemented by the target object will be exposed—in this case, the application's Clinic service interface.
From the point of view of a client, the "clinic" bean is just an implementation of the application's Clinic interface. The client does not have to know that it is dealing with a transactional proxy. This is the power of interfaces at work: A direct reference to the target object can easily be replaced with a proxy that implements the same interface—in this case, a proxy that implicitly creates transactions.
The concrete transactional behavior of a proxy is driven by transaction attributes for specific methods or method name patterns, as shown in the example below:
PROPAGATION_REQUIRED,readOnly PROPAGATION_REQUIRED
The key attribute determines which methods should have transactional behavior added to them by the proxy. The most important part of such an attribute is the propagation behavior. The following options are available:
The first six strategies are analogous to EJB CMT, with the same constant names, and should therefore look immediately familiar to EJB developers. The seventh, PROPAGATION_NESTED, is a special variant provided by Spring: It requires a transaction manager that either works with the JDBC 3.0 Savepoint API to provide nested transaction behavior (such as Spring's DataSourceTransactionManager) or supports nested transactions through JTA.
The readOnly flag in a transaction attribute indicates that the corresponding transaction should be optimized as a read-only transaction. This is an optimization hint: Some transaction strategies will be able to perform significant optimizations in such a case, for example avoiding dirty checking ("flush" attempts) when using an Object/Relational Mapping tool such as Hibernate or TopLink.
There is also the option to define a "timeout" value in the transaction attribute, specifying the timeout for the transaction as number of seconds. In the case of JTA, this will simply be passed down to the J2EE server's transaction coordinator and will get interpreted accordingly there.
At runtime, a client will fetch a reference to "clinic" bean, cast it to the Clinic interface, and invoke operations such as loadPet or storePet on it. This will implicitly go through Spring's transactional proxy, with a "transaction interceptor" registered in front of the target object; a new transaction will be created, and then the call will be delegated to the JdbcClinic target method.
Figure 1 illustrates the underlying concept of an AOP proxy with an "advisor chain" and a target at the end. In this case, the only advisor will be a transaction interceptor that wraps transactional behavior around the target method. This is proxy-based AOP (Aspect-Oriented Programming) at work beneath the hood of Spring's declarative transaction facilities.

Figure 1. An AOP proxy with an advisor chain and a target at the end
For example, a web tier component in the PetClinic web application could perform a ServletContext lookup to get a reference to the Spring WebApplicationContext and in turn to the "clinic" bean managed there:
WebApplicationContext ctx =
WebApplicationContexUtils.getWebApplicationContext(servletContext);
Clinic clinic = (Clinic) ctx.getBean("clinic);
Pet pet = new Pet();
pet.setName("my new cat");
clinic.storePet(pet);
At the beginning of the storePet() call, Spring's transactional proxy will implicitly create a transaction. When the storePet() call returns, the transaction will be committed or rolled back. By default, any RuntimeException or Error thrown will lead to a rollback. The actual rules for when to commit and when to roll back can be specified: Spring's transaction attribute supports a concept called "rollback rules."
For example, we could introduce a checked PetClinicException and tell the transactional proxy to roll back when that exception is thrown:
PROPAGATION_REQUIRED,readOnly,-PetClinicEception PROPAGATION_REQUIRED,-PetClinicException
There is also an analogous syntax for "commit rules," indicating specific exceptions that should trigger a commit.
Note that an explicit lookup as shown above is just the generic variant to get access to a Spring-managed bean, working in any web resource such as a servlet or a filter. When building a web tier with Spring's own web MVC framework, such beans can be injected directly into web controllers. Support for convenient access to Spring beans is also available for Struts, WebWork, JSF, and Tapestry, for example. Refer to the Spring documentation for details.
PlatformTransactionManager strategyThe core interface in Spring's transaction support is org.springframework.transaction.PlatformTransactionManager. All of Spring's transaction demarcation facilities delegate to a PlatformTransactionManager for actually executing transactions, passing in appropriate TransactionDefinition instances. While the PlatformTransactionManager interface can be used directly, applications usually just configure a concrete transaction manager and use declarative transactions to demarcate transactions.
Spring comes with a variety of PlatformTransactionManager implementations, which fall into two categories:
org.springframework.jdbc.datasource.DataSourceTransactionManager and org.springframework.orm.hibernate.HibernateTransactionManager. org.springframework.transaction.jta.JtaTransactionManager, delegating to a transaction coordinator that follows the JTA specification (usually but not necessarily, a J2EE server). The main value of the PlatformTransactionManager abstraction is that applications are not tied to a specific transaction management environment. Instead, the transaction strategy can be switched easily—through choosing a different PlatformTransactionManager implementation class. This allows the application code and declarative transaction demarcation to stay the same, no matter which environment an application component is used in.
For example, a basic version of an application might be deployed to Tomcat, talking to a single Oracle database. It can leverage convenient Spring transaction demarcation there, choosing the JDBC DataSourceTransactionManager as its transaction strategy. Spring will demarcate the transactions, and the JDBC driver will execute corresponding plain JDBC transactions.
A different version of the same application might be deployed to WebLogic Server, talking to two Oracle databases. The application code and the transaction demarcation do not have to change. The only adaptation required is to choose JtaTransactionManager as the transaction strategy, letting Spring demarcate the transactions and WebLogic Server's transaction coordinator execute the transactions.
UserTransaction versus JTA TransactionManagerLet's look at some details of how Spring's JTA support works. While it is helpful to understand this mechanism, it is often not necessary to worry about it. For simple use cases like the one shown in the previous section, a standard JtaTransactionManager definition is all that's needed, in combination with XA-aware DataSources provided by the J2EE server.
A default Spring JtaTransactionManager setup will fetch the JTA's javax.transaction.UserTransaction object from the standard JNDI location specified for it by J2EE: java:comp/UserTransaction. This is fine for most use cases in a standard J2EE environment.
However, a default JtaTransactionManager will not be able to perform transaction suspension (that is, it won't support PROPAGATION_REQUIRES_NEW and PROPAGATION_NOT_SUPPORTED). The reason is that the standard JTA UserTransaction interface does not support suspending or resuming transactions; it only supports beginning and completing new transactions.
To make transaction suspension work, a javax.transaction.TransactionManager instance needs to be supplied, which offers standard suspend and resume methods, as specified by JTA. Unfortunately, J2EE does not define a standard JNDI location for the JTA TransactionManager! Consequently, vendor-specific lookup mechanisms have to be used.
vendorSpecificJndiLocation
J2EE essentially does not consider the JTA TransactionManager interface part of its public API. The JTA specification itself declares the TransactionManager interface as intended for container integration. While this is understandable, a standard JNDI location for the JTA TransactionManager would still add significant value, in particular for lightweight containers such as Spring; the JTA TransactionManager of any J2EE server could then be located in a uniform manner.
Not only will Spring's JtaTransactionManager benefit from access to the JTA TransactionManager, but O/R mapping tools such as Hibernate, Apache OJB, and Kodo JDO will benefit too, as they need this to be able to perform cache synchronization in a JTA environment—that is, releasing cache locks at JTA transaction completion. The ability to register transaction synchronizations is only offered by the JTA TransactionManager interface, not by the UserTransaction handle. As a consequence, each of these tools needs to implement its own vendor-specific TransactionManager lookup adapters.
Defining a standard JNDI location for the JTA TransactionManager is high on the J2EE wish list of many infrastructure software providers. It would be great if the J2EE 5.0 specification team would recognize the importance of this feature. Fortunately, advanced J2EE servers such as WebLogic Server already consider their JTA TransactionManager a public API, including vendor-specific extensions!
In the case of WebLogic Server, the official JNDI location of the JTA TransactionManager is javax.transaction.TransactionManager. This value can be specified as "transactionManagerName" on Spring's JtaTransactionManager. In principle, this enables Spring-driven transaction suspension with WebLogic's JTA subsystem, activating the support for PROPAGATION_REQUIRES_NE and PROPAGATION_NOT_SUPPORTED.
javax.transaction.TransactionManager
Beyond its standard JtaTransactionManager and the general configuration options supported there, Spring also provides a special WebLogicJtaTransactionManager adapter that leverages WebLogic's JTA extensions directly.
In addition to the convenience of auto-detecting WebLogic's JTA TransactionManager, this enables three important features that go beyond standard JTA:
TransactionManager interface beneath, calling the forceResume() method. The following screenshot shows WebLogic Server's transaction monitor, which lists a couple of Spring-driven transactions by name:
|
Effectively, Spring's WebLogicJtaTransactionManager exposes the full power of WebLogic Server's transaction manager to Spring-based applications. This makes Spring transaction demarcation a compelling alternative to EJB CMT and provides the same level of transaction support.
Note that the WebLogic-specific JTA setup is only necessary when there is an actual need for transaction suspension or for leveraging WebLogic's JTA extensions. For standard transaction demarcation such as PROPAGATION_REQUIRED or PROPAGATION_SUPPORTS, the standard JTA setup will be fine.
As illustrated above, Spring's declarative transaction demarcation for POJOs can be considered an alternative to traditional EJB CMT. However, Spring and EJB are not mutually exclusive. A Spring application context can also serve as a back end behind EJB facades, managing data access objects (DAOs) and other fine-grained business objects.
In an EJB scenario, transactions will be driven by EJB CMT. Spring's data access support will automatically detect such an environment and adapt accordingly. For example, Spring's Hibernate support will provide its implicit resource management even with such EJB-driven transactions, just like it would with Spring-driven transactions. It will even provide the same semantics and not require any modification to DAO code.
Spring effectively decouples DAO implementations from the actual runtime environment. DAOs can participate in Spring transactions (with any transaction strategy as the back end) as well as EJB CMT transactions. This not only allows for reuse in other environments, but it also allows for straightforward use in tests outside the J2EE container.
The Spring Framework offers full-fledged transaction demarcation facilities for both J2EE and non-J2EE environments, in particular declarative transactions for plain Java target objects. This enables convenient transaction demarcation without EJB, in a flexible and non-intrusive fashion. In contrast to EJBs, such transactional POJO application objects can easily be tested or reused outside a J2EE container.
Spring provides various out-of-the-box transaction strategies, such as JtaTransactionManager, which delegates to the J2EE server's transaction coordinator, and the JDBC DataSourceTransactionManager, which executes transactions for a single JDBC DataSource (that is, a single target database). Spring can easily adapt the transaction strategy to a different environment through a simple change in back-end configuration.
Beyond standard JTA support, Spring provides sophisticated integration with WebLogic Server's JTA extensions, allowing for advanced features like transaction monitoring and per-transaction isolation levels. Through this special WebLogic Server support, the full power of WebLogic's transaction manager becomes available to Spring-based applications.
Spring transaction demarcation is a compelling alternative to EJB CMT, in particular in combination with a POJO-based lightweight architecture. In a scenario where the only reason for choosing Local Stateless Session Beans would be declarative transactions, a Spring-based POJO service model is a viable option, offering a significantly higher level of flexibility, testability, and reuse.
Participate in the uture of Java
Participation is Sun's theme for JavaOne 2005, as repeatedly preached by speakers in the general sessions of the two days that opened this week's developer conference. The idea was captured early by emcee John Gage, Sun's chief researcher and science office director, who began the first day by asking developers to stand up, then by asking all CTOs, VCs and other deal-makers to stand up. "OK, programmers," he said, "there's who you have to meet."
留个记号
一周前,在公司下面健身房锻炼时腹部肌肉拉伤了。过了一周才好。郁闷。现在好了高兴。申懒腰不会疼了,嘿嘿
。没有想到放假了我还是这么忙。寒~~~今天还去篮球了哈哈。现在觉得累累的,明天还要去公司。
:( 今天又在网上看见vk了,假期偶尔看见她上线,总是冒几个泡泡就溜了。
是时候我再奋斗一次了。本来就应该过得多姿多彩,有激情的嘛,哈哈。这次与以往不同,以前是学校,现在不同了。想信 我能够把工作做到最好。
这几天好热
这几天好热啊
热得砩纤蛔?/p>
小天招新终于完成了
现在可以安心的复习了
看见他们那么有激情
那么有斗志
我也放心了许多
小天这一年,也经历了不少大小事情啊
也算终于挺过来了
真是一言难尽啊
下学期应该可以完全放手了
现在正在调整发展方向。
我在这里给我自己存偌,
我离开小天时一定会大干一场。
让大家知道我们小天是最好的。
最近和书记联系了不少商家和公司
正在为解决小天经费问题。
我相信小天的饿明天是美好的。
新进的兄弟姐妹也记得要加油!!
有朋友叫我陪她去听答辩,美女哦
恩先写到这里了
等会还要去上自习
郁闷这几天锻炼时受伤了
左臂受伤了,好痛动都不敢怎么动。
尽管这样还是没有去看医生
自己找了一张什么跟什么来贴到起

再来一张,嘿嘿~~

白忙中抽了一天时间更新新了新闻系统
花了我周五整天时间.
我还逃了3节课.
加上一个晚上终于把新闻.
更新了,迁移到了MSSQL.
数据库下.
当时由于这边登陆不了服务器
昨天晚上,没有把新的系统放上去.
今天下午看看了.
结果 小邹还没放上去.
还是我去弄了好了.
弄了几分钟就搞顶了.
今天晚上和明天还要忙~~~
汗~~~
还是在公司舒服点.........
5555555555
至少不用这么忙...........