Posts Tagged ‘spring’

Using @Scheduled annotation in spring

August 12th, 2015 No comments

If you are looking to scheduled task and are using spring framework, there are couple of alternatives

a) Quartz : Spring has support for quartz

b) @Scheduler annotation : Simple and easy.

Here is the code sample

public class SchedulerManager {

 @Scheduled(fixedRate = 10000)
 public void testMyScheduler(){

System.out.println(" I am the scheduler >>>>>>");

10000 is in milliseconds so you would see output after 10 seconds .

If you want to start after some delay and not at application start up

public class SchedulerManager {

@Scheduled(initialDelay=2000, fixedRate = 10000)
public void testMyScheduler(){

System.out.println(" I am the scheduler >>>>>>");

The method gets executed after delay of 2 seconds.

And if you want to use cron expression

public class SchedulerManager {

@Scheduled(cron="0 0/1 * * * ?")
public void testMyScheduler(){

System.out.println(" I am the cron scheduler >>>>>>");

The above method executes after 1 minute.

Remember spring calls it a cron expression but in fact it is not a true cron expression. If you use the actual cron expression , you would see some exception like

Caused by: java.lang.IllegalStateException: Encountered invalid @Scheduled method ‘testMySchedulerWithQuartz': Cron expression must consist of 6 fields (found 7 in “0 0/1 * * * ? *”)

And here is the simple applicationContext.xml file

 <task:annotation-driven />
 <bean id="scheduleManager" class="com.skg.demo.scheduler.SchedulerManager" />

The output after 10 seconds will be

I am the scheduler >>>>>>

I am the scheduler >>>>>>

I am the scheduler >>>>>>

You do not need any other configuration setup

Spring has complete documentation on various strategies

NFJS in Boston this weekend

February 27th, 2015 No comments

I will be attending NFJS for next 3 days scheduled to start from today 02/27 and will run for next 3 days. Conference will focus on the latest technologies and best practices emerging in the Java / JVM software development space

NFJS at Boston

Excited to see lots of topics which I plan to attend. I will post about few topics on this blog next week.

Follow us on twitter @skillguru and NFJS at @nofluff



Categories: Tech news Tags: ,

How to enable Load Time Weaving of Aspects in Spring

February 9th, 2015 No comments

We will talk about weaving in general and how to enable weaving in your spring application. You would have heard of weaving mostly with AOP programming and normally with Spring, but before we dive into Spring AOP, let us understand weaving.

What is weaving in programming ?

Weaving in general is a programmatic transformation which essentially means processing of a code to produce a desired output.

In Spring AOP makes it possible to modularize and separate logging, transaction like services and apply them declaratively to the components Hence programmer can focus on specific concerns. Aspects are wired into objects in the spring XML file in the way as JavaBean. This is also known as ‘Weaving’.

There are three types of weaving

  • Compile time
  • Post compile time
  • Run time

We can have source level weaving as in C++ using pre processors. In Java we can have byte code in which you add code at run time around your existing code.

The AspectJ weaver takes class files as input and produces class files as output. The weaving process itself can take place at one of three different times: compile-time, post-compile time, and load-time. The class files produced by the weaving process (and hence the run-time behaviour of an application) are the same regardless of the approach chosen.

  • Compile-time weaving is the simplest approach. When you have the source code for an application, ajc will compile from source and produce woven class files as output. The invocation of the weaver is integral to the ajc compilation process. The aspects themselves may be in source or binary form. If the aspects are required for the affected classes to compile, then you must weave at compile-time. Aspects are required, e.g., when they add members to a class and other classes being compiled reference the added members.
  • Post-compile weaving (also sometimes called binary weaving) is used to weave existing class files and JAR files. As with compile-time weaving, the aspects used for weaving may be in source or binary form, and may themselves be woven by aspects.
  • Load-time weaving (LTW) is simply binary weaving defered until the point that a class loader loads a class file and defines the class to the JVM. To support this, one or more “weaving class loaders”, either provided explicitly by the run-time environment or enabled through a “weaving agent” are required.

You may also hear the term “run-time weaving”. We define this as the weaving of classes that have already been defined to the JVM (without reloading those classes). AspectJ 5 does not provide explicit support for run-time weaving although simple coding patterns can support dynamically enabling and disabling advice in aspects.

We are going to show compile time weaving in the application. A preprocessor and aspect weaver are used to transform the original non-aspect code into a woven code. Thus, the original code is altered only once at compile-time.

Why did we use compile time weaving ? Because it leads to quicker startup time in your application. Drawback is that anytime the aspect gets modified, all code segments which are weaved by this aspect, must get recompiled.

Steps to enable Load Time Weaving of Aspects in your application

Step 1:

Add the following to your application context to inform Spring to activate the AOP injection.


Step 2:
Add the @Configurable annotation to your entity. Use @Autowired annotation to inject dependencies

public class MyClass{
Private transient MyRepository


Step 3:
To tell Spring/AspectJ which domain objects are going to be “woven”. Create a new directory “META-INF” in a directory which is included on the classpath. Add inside this directory a new file called “aop.xml”.

NOTE: Use the most restrictive packages possible. The smaller the code base inspected and instrumented, the faster startup time will be and the less runtime overhead

Add the following to that file:

"-//AspectJ//DTD//EN" "">
<weaver options="-Xreweavable -showWeaveInfo  -XmessageHandlerClass:org.springframework.aop.aspectj.AspectJWeaverMessageHandler">
<exclude within="*..*CGLIB*" />
<exclude within="*..*javassist*" />
<include within="com..*.mypackage..*"/>
<aspect name="org.springframework.beans.factory.aspectj.AbstractInterfaceDrivenDependencyInjectionAspect"/>

This adds the @Configurable support to those beans included in any sub package of the “com…*.mypackage” package and excludes files from CGLIB or javaassist packages and resolves weird errors related to cglib proxy class or javaassist. Step 4: Finally, you must tell the JVM to use the AspectJ “Java Agent”. This is needed for AspectJ to intercept method calls.This can be enabled when starting the JVM using the following argument:


New Spring Mock Certification Exam

March 4th, 2012 2 comments
Elric has added a new Spring Mock certification Practice test for our readers . The questions are close to the real exam and will help you in practicing for the test or to test your Spring proficiency
Test Details : 50 questions, 88 minutes to complete and a minimal score of 76% to reach (38 right questions)
Repartition of the questions  by category:
  • Container  (13)
  • Test (5)
  • AOP (10)
  • Data Access (5)
  • Transactions (5)
  • Spring MVC (3)
  • Spring Security (3)
  • Remoting (2)
  • JMS (2)
  • JMX (2)

Please take the test and give your feedback to Elric. Thanks to Elric for taking out time to create the test and share with the community

New practice test on Spring Certification

July 24th, 2011 No comments

After huge success of last two Spring mock tests from ikoko, Jacek has added another test for our readers .

Spring 3.x certification mock test

Questions very similar to originals with almost the same difficulty level. Majority questions are from most important sections at exam: container, testing, AOP, transactions. Only few from other sections like MVC, REST, JMX, JMS.

This is a 30 question practice test. 5 questions are free for you to try.

It is very reasonably priced at $1.99.

If you buy all there tests, you would save on paypal fees.

I am sure you would like the test. Jacek is looking for feedback and inputs to make the test better.

Categories: Programming / tutorials Tags:

Reading properties file in Spring

June 5th, 2011 2 comments

There are multiple ways to read properties file in Spring

Let us say you have database user name , password etc configured in and would like to inject the values at run time.

Here is what will go in applicationContext.xml

<bean id=”propertyConfigurer”>
<property name=”locations”>

<bean id=”dataSource” destroy-method=”close”>
<property name=”driverClass” value=”${jdbc.driverClass}”/>
<property name=”jdbcUrl” value=”${jdbc.url}”/>
<property name=”user” value=”${jdbc.user}”/>
<property name=”password” value=”${jdbc.password}”/>
<property name=”minPoolSize” value=”${jdbc.minPoolSize}”/>
<property name=”maxPoolSize” value=”${jdbc.maxPoolSize}”/>

and this will be your properties file


At run time, the properties file value will be injected  into the applicationContext.xml

How FlushMode.Never affects the performance ?

May 20th, 2011 No comments

In hibernate if you set this in you code


What does it signify ?

It means that the Hibernate session not to flush any state changes to database unless flush() is explicitly called by the application.

When setting the FlushMode.NEVER , will it improve the performance and reduce the run time  ?

It would not affect if you are running a single update or a series of small updates. It really affects you when you are doing batch processing. The reason for this is the way hibernate implements dirty checking. Once you load an object in memory and do not evict it, the hibernate session keeps track of it in case if it was changed. So, any time you perform a query, the session iterates over all objects in the session checking dirtiness and flushes any dirty objects to the database. It does this to ensure that all state changes that might affect the query are present in the database before issuing the query to it. That’s fine when you have only a few objects in session, but when you have thousands and are performing thousands of queries, it becomes a real drain on performance.

Tim fennel has made this interesting observation about the FlushMode.NEVER in his blog here.

Spring provides a similar way to annotate methods @Transactional(readOnly=true) in Spring which internally has the same affect.

Spring certifications tests at Skill-guru

May 2nd, 2011 No comments

For users  who have been taking the Spring certification practice tests 1 and  Spring certification practice tests 2 at skill-guru  have raise the concern that

We have contacted the creator of these tests Ikoko , and he has clarified thatthe Spring documentation for the exam syllabus has changed (improved) since he had created the exam so the tests now appear to be different to the syllabus

The historical documentation and support for the certification has been poor from Spring and might even be incorrect.

he also pointed out that Skill-guru test-takers basing their opinions on the Spring documentation and not actually doing the Spring exam are therefore possibly misled by the official documentation

From Ikoko’s email

I sat both the 2.5 exam and 3.0 exam so have experienced both exams first-hand and have been keen to keep my exams accurate based on real exam-experience and not any vague syllabus published by Spring

Having said all, this at a higher topic level I only noticed the category of SpEL (Spring expression language) being a category in my tests that was not in the offical syllabus. I had 1 SpEL question in test 1, and 2 questions in test 2. I have now removed all three questions.

Hope  this clarifies the doubt of our readers and thanks to MaggieL and Shane Mannion for pointing this out