Technical Blog

3 Posts tagged with the java tag

Hello all,

 

In a recent project we began using the @Autowired spring annotation in our objects and services to help simplify and minimize the amount of configuration we were writing in our various xml files.

 

Introduced in Spring 2.5 annotation-based configurations are now a viable alternative to pure XML configuration.  While it is debatable if one approach is “better” than the other, in practice it seems that mixing both methods allows you to spend less time wiring everything up and just getting on with it.

 

There are a number of annotations available including support for JSR-250 and JSR-330 but for this article I will be focusing purely on the @Autowired annotation.  For more information please refer to the Spring documentation or any number of articles on the web.

 

What’s the point?

 

How many times have you had to explicitly wire your spring beans and services hunting for the proper bean names?  What about creating setter methods for your private objects?  What if there were an easier way to do it?

 

Spring 2.5 (and beyond) has introduced a new xml context schema that deals with ApplicationContext configuration related to plumbing – that is, not usually beans that are important to an end-user but rather beans that do a lot of the grunt work in Spring, such as BeanFactoryPostProcessors.  To enable the tags in the context namespace, simply add the context namespace to your schema definition:

 

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<!-- <bean/> definitions here -->

</beans>

 

 

Now let’s look at a class as an example to see how @Autowired can help you in your daily development.

 

package emptest;
public interface EmployeeService {
         String hire(String name);
         String fire(String name);
}
 
 
package emptest.impl;
@Service
public class EmployeeServiceImpl implements EmployeeService {
 
         private EmployeeDao employeeDao;
 
         public String hire(String name) {
                 String message = employeeDao.getMessage("Hire");
                 return name + ", " + message;
         }
 
         public String fire(String name) {
                 String message = employeeDao.getMessage("Fire");
                 return name + ", " + message;
         }
 
         public void setEmployeeDao(EmployeeDao employeeDao) {
                 this.employeeDao = employeeDao;
         }
}
 

 

In this simple example we have a service implementing an interface with a private DAO object.  In a typical spring configuration for this service typically you would define your bean as:

 

 

<bean id="employeeService" class="emptest.impl.EmployeeServiceImpl">
         <property name="employeeDao">
                 <ref bean=”employeeDao”/>
         </property>
</bean>

 

 

But Spring can automatically detect classes and register bean definitions with the ApplicationContext!  Let’s see how this works in practice.

 

Step 1.  Add <context:component-scan base-package=”emptest.impl”/> to your configuration file.  This tells spring to scan everything in the emptest.impl package for Spring stereotypes and annotations.

 

 

<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
     xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

     <context:component-scan base-package="emptest.impl"/>


</beans>

 

 

Step 2.  Add @Autowired annotation to any private objects that you would like Spring to wire up for you.

 

package emptest.impl;
@Service
public class EmployeeServiceImpl implements EmployeeService {
         @Autowired
         private EmployeeDao employeeDao;
 
         public String hire(String name) {
                 String message = employeeDao.getMessage("Hire");
                 return name + ", " + message;
         }
 
         public String fire(String name) {
                 String message = employeeDao.getMessage("Fire");
                 return name + ", " + message;
         }        
}
 
 

 

That’s it!  Notice that there is no need to explicitly define a setter method, nor do you need to explicitly define your bean within the Spring configuration.

 

Of course this is a very basic scenario, but for the most part will get you started using annotation based configuration.  There are lots of tutorials, guides and documentation available online for more advanced usages.

 

Cheers!

1 Comments Permalink

Elastic Path Commerce version 6.2 was released in January with little fanfare, but don’t let that fool you; 6.2 is packed with lots of advanced ecommerce features. This release was all about giving merchants more flexibility in terms of how they sell their products. One of the big features we added was bundling (or kitting, if you prefer). Bundling gives merchants the ability to configure groups of products that can be sold as package deals. This gives their customers greater value and simplifies their purchase decisions. For merchants who wish to give their customers the value of package deals, but flexibility of choice, they can use dynamic bundles. Dynamic bundles give customers the choice between several merchant-defined options.

 

Many merchants will also be happy to learn that we've moved prices out of the catalog and into price lists. And by linking price lists to our targeted selling framework,  we’ve given merchants the ability to target price lists to different markets and customer segments. For B2B merchants, price lists are a great way to manage negotiated contract pricing for different accounts.

 

In 6.2, we've also introduced the ability to personalize products. By creating a configurable product type, merchants can give their customers the power to customize products before checkout. A good example would be a custom screening printing site that allows shoppers to upload the designs they want to print on their T-shirts.

 

For store managers and IT staff involved in store operations, the new staging to production feature will be tremendously useful. It allows changes to products, prices, promotions and marketing content to be previewed in a staging environment, and submitted for review and approval before being pushed over to the production environment.

 

For the tech folks, the 6.2 release includes support for new versions of various application servers, Java 6 support, and an upgrade to JPA 1.2.1. Storefront performance has also been improved with the addition of multi-level caching and other performance enhancements. 6.2 includes upgrade scripts, which should allow existing clients to upgrade quickly and make use of all the new features that 6.2 has to offer.

 

For more information, check out the 6.2.0 release notes and stay tuned for blog posts looking more in depth at some of these exciting, new features.

0 Comments Permalink

Performance testing is a task often left to the last stages of software development, after the code is checked in, passed QA for functional testing, and no longer fresh in the minds of developers who wrote it. With JUnitPerf, you can leverage your existing suite of JUnit tests to get performance measurements while you're developing. The framework provides easy to use decorator classes for creating:

 

  • Timed tests to measure execution time
  • Load tests for measuring how your code runs with multiple requests

 

Performance tuning should always be done with a performance goal in mind, and JUnitPerf shouldn't be the end all measurement tool for the performance your code. Instead it is more useful for

 

  • Getting a basic idea of where your execution bottlenecks may lay
  • Evaluating the performance difference between multiple technical solutions
  • Uncovering immediate concurrency issues

 

JUnitPerf uses decorator classes to wrap existing JUnit tests. This makes it possible to add performance measurements even to HttpUnit or DbUnit tests.

In our examples we will use the following unit test

public class SimpleUnitTest extends TestCase {
...
  public void test1() {
      ... //some operations
  }
...

 

A TimedTest can be used to provide a time limit for your running tests. Tests will fail if they take longer than the given time limit to execute. This is useful if you know you don't want to exceed a certain time constraint. Here we are running all tests within the SimpleUnitTest class as a suite with a time limit of 1 second.

public class SimplePerfTest {
  public static void main(String[] args) {
    int timeLimit = 1000;
    Test timedTest = new TimedTest(new TestSuite(SimpleUnitTest.class), timeLimit);
    junit.textui.TestRunner.run(timedTest);
  }
}

 

You can use LoadTest to create a load test with a specified number of threads(JVM will constrain the upper thread limit) running your test case either simultaneously or at randomly dispersed start times. We will do the simplest example of running a test suite with 100 threads concurrently.

public class SimplePerfTest {
  public static void main(String[] args) {
    int load = 100;
    Test loadTest = new LoadTest(new TestSuite(SimpleUnitTest.class), load);
    junit.textui.TestRunner.run(loadTest);
  }
}

 

In a more complex example of using LoadTest, we can simulate 100 threads running our test code, with a random delay before the addition of each concurrent thread. In addition to the RandomTimer class to specify a delay, there is also the ConstantTimer to specify a constant delay between thread addition.

public class SimplePerfTest {
  public static void main(String[] args) {
    int threads = 100;
    int delay = 10;
    int randomVariation = 20;
    Timer randomTimer = new RandomTimer(delay, randomVariation);
    Test loadTest = new LoadTest(new TestSuite(SimpleUnitTest.class), threads, randomTimer);
    junit.textui.TestRunner.run(loadTest);
  }
}

 

Lastly, we can combine both TimedTest, LoadTest, and RepeatedTest (part of JUnit) to string together a rather sophisticated concurrent performance test. Here's a test that concurrently runs your unit test in 100 threads, each repeating 10 times before ending, with a time limit of 2 seconds for the test to complete. Threads are being added after every 10ms by using the ConstantTimer.

public class SimplePerfTest {
  public static void main(String[] args) {
    int timeLimit = 2000;
    int threads = 100;
    int delay = 10;
    int repetitions = 10;
    Timer randomTimer = new ConstantTimer(delay);
    Test timedTest = new TimedTest(new TestSuite(SimpleUnitTest.class), timeLimit);
    Test repeatedTest = new RepeatedTest(timedTest, repetitions);
    Test loadTest = new LoadTest(repeatedTest, threads, randomTimer);
    junit.textui.TestRunner.run(loadTest);
  }
}

 

JUnitPerf tests are great for quickly spotting performance problems early in the development cycle, requiring very little extra work if your regular coding practice already includes JUnit, and extensions of JUnit such as HttpUnit and DbUnit. With multithreaded LoadTests, it can also be helpful in uncovering concurrency issues normally difficult to discover with code inspection or other forms of testing. There is unquestionable value in performing performance testing on a fully functional and integrated system, but you can cut down both cost and risk to your project by validating the performance of your designs early, especially architectural decisions that may be hard to change later on (though being Agilists, we always try to make change easy. But that's a topic for another day).

 

 

Resources:

http://clarkware.com/software/JUnitPerf.html

Home of JUnitPerf

 

http://junit.org

Home of JUnit

 

http://www.dbunit.org/

Home of DbUnit

 

http://httpunit.sourceforge.net/

Home of HttpUnit

 

http://www.ibm.com/developerworks/java/library/j-cq11296.html

Performance testing with JUnitPerf

0 Comments Permalink