Archive

Posts Tagged ‘spring’

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.

</pre>
<div>
<pre><context:spring-configured/>

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

</pre>
<div>
<pre>@Configurable
public class MyClass{
...
@Autowired
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:


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

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:

</pre>
<div>
<pre>-javaagent:c:/devtk/LAS/lib/spring-instrument.jar

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 jdbc.properties and would like to inject the values at run time.

Here is what will go in applicationContext.xml

<bean id=”propertyConfigurer”>
<property name=”locations”>
<list>
<value>classpath:environment.properties.properties</value>
</list>
</property>
</bean>

<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}”/>
</bean>

and this will be your properties file

jdbc.driverClass=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@abc.com:1521:ORAC
jdbc.user=hello
jdbc.password=hello
jdbc.minPoolSize=1
jdbc.maxPoolSize=10

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

session.setFlushMode(FlushMode.NEVER)

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

Spring JdbcTemplate batch Update-Insert example

April 12th, 2011 1 comment

This post explain how to use Spring JDBCTemplate to do batch insert and update.

If you are using SimpleJDBCtemplate then the Spirng docs are good place to find a good explanation for it Simple JDBC Template

If you are using JDBCtemplate , here is the example to use prepared statements and do batch updates

public boolean createGroceyList(List<Grocery> groceryList){

final List<Grocery> aGroceryList =  groceryList

int result[] = this.jdbcTemplate.batchUpdate(

“the query goes here “,new BatchPreparedStatementSetter() {

public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setLong(1, “param 1 goes here “);
ps.setString(2, “param 2 goes here “);

ps.setString(3, “param 3 goes here “);
}

public int getBatchSize() {
return aGroceryList.size();
}
});

return (aGroceryList.size() == result.length ? true : false);
}

The query would be something similar to

INSERT INTO GROCERY(ID, NAME, QUANTITY) VALUES(?,?,?)

Categories: Programming / tutorials Tags: ,