Saturday, November 21, 2009

AOP - AspectJ,Spring - Compile Time ,Load Time ,Run Time(Proxy)

Spring AOP - Runtime - Using Proxy


1.Spring Application Context - Bean Declarations

For enabling this proxy approach add
<aop:aspectj-autoproxy />

Note :

Do not be misled by the name of the element: using it will result in the creation of Spring AOP proxies. The @AspectJ style of aspect declaration is just being used here, but the AspectJ runtime is not involved

Aspect Declaration
<bean id="myAspect" class="com.test.aop.MyAspect"></bean>

Method where aspect will be applied
<bean id="test" class="com.test.aop.Test" init-method="init" />

Wrapper calling test
<bean id="testB" class="com.test.aop.Wrapper" init-method="init">
<property name="test" ref="test"></property>

2. Classes

  • Aspect Class

public class MyAspect {

@Before("execution(* com.test.aop.Test.*())")
public void myMethod()
System.out.println("calling my before aspect");


  • public class Test {

public void init()
System.out.println("init in test method");


  • public class Wrapper {

private Test test;

public void setTest(Test test) {
this.test = test;

public void init() {


3. OutPut(In Spring DM)

System.out I init in test method
System.out I calling my before aspect
System.out I init in test method

Only when the init method is called through testB bean ,the aspect is bound.

Now when init method of test bean is called , the aspect is still not bound.(init methods cannot be proxied).

This is because the way spring life cycle works :

Spring life cycle

Phase 1 - Validate bean definitions
Phase 2 - Bean definition post processor(replacing property values)
Phase 3 - Bean Instantiation
Phase 4 - Bean post initialization(setters and init methods -in order) & Proxy creation

In the above example bean 'test' first cycles through phase 1,2,3 and 4. Hence after the init method is called, the proxy is created.But when testB is created in its init(phase) call to bean test will call teh aspect (as bean test lifecycle is complete)

One more important thing to note is that Cg lib will be used to create proxy here as teh class doesnt implement any interface.(Else jdk dyanmic proxies would have been used)

Aspect-J Load Time Weaving
(This may have issues with Spring DM

Same code as above except some change in the configurations.

1. Replace <aop:aspectj-autoproxy /> with <context:load-time-weaver/>.

2. Add aop.xml in META-INF directory

"-//AspectJ//DTD//EN" "">

<!--works without this -->
<include within="com.test.aop.*" />

<!-- weave in just this aspect -->
<aspect name="com.test.aop.MyAspect" />


3. Class to test the application in standlone mode

public class StandAloneLoadTimeWeaving {

public static void main(String args[])
ApplicationContext ctx = new ClassPathXmlApplicationContext("config.xml",StandAloneLoadTimeWeaving.class);
Test t =(Test)ctx.getBean("test");



4. Add the following parameter when running


Aspect J Compile Time Weaving(Build Time)

Same as Loadtime weaving needs aop.xml (but no need to add spring agent while running)

Command to compile the code

java –inpath <src_code_directory> -outjar <output_jarname.jar>

Ex:java -cp aspectjtools.jar;aspectjrt.jar -inpath . -outjar test.jar

The output jar will have code which is instrumented by the aspect.

You can download aspectj from this site

Wednesday, November 18, 2009

Writing Custom Namespaces in Spring

1. Application context xmls looks as below

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

<test:person name="suji"/>

Now the xsd mentioned in the schema location should map to something.

2. You shoudl have a spring.schemas file in the META-INF directory


This maps the schema to teh lcoation of teh xsd

3. Xsd looks like


<xsd:element name="person">
Configures all required interactions with the named Control Bus configuration
<xsd:attribute name="name" type="xsd:string">
Identifies group-name of a Control Bus this configuration defines


We have a single element person with attribute as name which is a string.

4. Now each element in the xsd should map to a resolver.

This can be mentioned in spring.handlers file which is also in the META-INF directory


5. Implementaion of PersonNamespaceHandler

import org.springframework.beans.factory.xml.NamespaceHandlerSupport;

public class PersonNamespaceHandler extends NamespaceHandlerSupport {
public void init() {
registerBeanDefinitionParser("person", new PersonParser());


6. Parser implementation

public class PersonParser extends AbstractBeanDefinitionParser {
private String beanName;

/* This method gets the parameters mentioned in the custom namespace and helps building
custom logic based on it */

protected AbstractBeanDefinition parseInternal(Element element,
ParserContext parserContext) {
BeanDefinitionBuilder rootBuilder = BeanDefinitionBuilder
beanName = element.getAttribute("name");

//Ensuring name is a compulsary attribute

Assert.hasText(beanName, "'name' must be provided");
rootBuilder.addPropertyValue("name", beanName);
return rootBuilder.getBeanDefinition();

protected String resolveId(Element element,
AbstractBeanDefinition definition, ParserContext parserContext)
throws BeanDefinitionStoreException {
return beanName;


7. Custom classes for Person

public class Person {

private String name;

public String getName() {
return name;

public void setName(String name) { = name;

Test case for trying out this

public class PersonParserTest {

public static void main(String[] arg){
ApplicationContext ac = new ClassPathXmlApplicationContext("config.xml", PersonParserTest.class);
Person person = (Person) ac.getBean("suji");
System.out.println("Person: " + person.getName());

Tuesday, November 17, 2009

TCCL in OSGi(Spring DM)

In order to better understand how TCCL works in OSGi i have done a sample POC.

I created 3 bundles.

Bundle A - calls Bundle B (imports Bundle B)

Bundle B -calls Bundle C (imports Bundle A)

Bundle C - instantiates class in Bundle A (No imports)

In normal cases Bundle C will fail to instantiate class in Bundle A, but this can be achieved using TCCL as follows.

ITest test=(ITest)Thread.currentThread().getContextClassLoader().loadClass("com.bundleA.external.ActionClass").newInstance();

Conclusion: Spring Dm sets TCCL to the bundle classloader where the thread initiated.

Now what if we want to instantiate class of bundle B in Bundle C , but the thread flow doesnt change. ?

This can be easily done by resetting the TCCL in bundle B's method as follows


BootClassPath and Sytem ClassPath in OSGI(Spring DM)

System Package

java.* can be directly used without any imports. This is neither part of boot delegation nor system packages as they are part of jdk itself.For loading these fundamental types, the OSGi platform uses parent delegation instead of the networking model; that is, it uses the class loader that started the OSGi framework to load classes instead of an OSGi class space.

None of the other public packages available in the JDK such as the or javax.xml are parent delegated which means they have to be resolved within the class space that is, bundles need to import the packages (which means there needs to be a provider) since they are not implied. The OSGi spec allows the Framework (through its system bundle) to export
any relevant packages from its parent class loader as system packages using the org.osgi.framework.system.packages property.

As repacking the hosting JDK as a bundle isn't a viable option, one can use this setting to have the system bundle (or the bundle with id 0) export these packages itself.

Extension Bundles

Another possible option is to enhance the system bundle through extension bundles. These act as fragments; they are not bundles of their own but rather are attached to a host.
Extension bundles are a special kind of fragments that get attached only to the System bundle in order to deliver optional parts of the Framework

Boot Delegation

This allows the user to create 'implied' packages that will always be loaded by the framework parent class loader, even if the bundles do not provide the proper imports:

This option is mainly created to accommodate various corner cases especially in the JDK classes that expect parent class loading delegation to always occur or that assume that every class loader on the system has full access to the entire boot path.There are cases where boot delegation is quite handy; a good candidate being instrumentation, such as profiling or code coverage.


I have done samples to better understand how classloader comes into picture for loading classes at different levels by printing parent classloaders upto 4 levels.

Class loader for one of the classes of bundle in pick up.

bundle classloader ServerBundleClassLoader: [bundle=ClassPathTest_1.0.0]
bundles parent
bundles parent sun.misc.Launcher$AppClassLoader@7d772e
bundles parent sun.misc.Launcher$ExtClassLoader@11b86e7

Class loader hierarchy for org.osgi.framework.BundleActivator

**************System bundle 0*******************
bundle classloader
bundles parent sun.misc.Launcher$AppClassLoader@7d772e
bundles parent sun.misc.Launcher$ExtClassLoader@11b86e7
I bundles parent null

Created a dummy class and added this in the classpath of dm server startup.bin.Also modified to include this java6-server.profile as org.osgi.framework.system.packages = \
(I did import this package in my test bundle)

*************SYSTEM PATH**************
bundle classloader sun.misc.Launcher$AppClassLoader@7d772e
bundles parent sun.misc.Launcher$ExtClassLoader@11b86e7
bundles parent null
I parent null

Created a dummy class and added this in the classpath of dm server startup.bin.Also modified to include this java6-server.profile as org.osgi.framework.bootdelegation = \
(Did not import this package in my test bundle)

*************BOOT PATH**************

bundle classloader sun.misc.Launcher$AppClassLoader@7d772e
bundles parent sun.misc.Launcher$ExtClassLoader@11b86e7
I bundles parent null
I parent null

Sunday, November 15, 2009

Configuring Component based logging in OSGi using Log4j

Initialize reading of the log4j xml in any of the core bundles. Ensure that this bundle doesnt get bounced often.Configure the values to include log4j xml and reload delay.The init method can look something similar to the one below.

public void initialize() {
try {
try {
String logConfig = "D://temp//poc_log_config.xml";
long configReloadDelay = (long) (1 * 30 * 1000);
if (logConfig != null && (new {
if (logConfig.endsWith("xml")) {
logConfig, configReloadDelay);
} else {
.configureAndWatch(logConfig, configReloadDelay);
} else {
} catch (Exception initErr) {
} catch (Exception err) {


The log4j xml will look as follows

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="">

<appender name="PRODUCT1" class="com.test.anyappender">
<param name="File" value="D:\\temp\\product1\\product1log.log"/>
<param name="MaxFileSize" value="100000000"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{HH:mm:ss,SSS} - %m%n"/>
<param name="Threshold" value="DEBUG"/>

<appender name="PRODUCT2" class="com.test.anyAppender">
<param name="File" value="D:\\temp\\product2\\product2.log"/>
<param name="MaxFileSize" value="100000000"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{HH:mm:ss,SSS} - %m%n"/>
<param name="Threshold" value="DEBUG"/>

<level value="OFF" />

<logger name="test1">
<appender-ref ref="PRODUCT1"/>
<level value="INFO" />

<logger name="test2">
<appender-ref ref="PRODUCT2"/>
<level value="DEBUG" />


Now in any bundle code you can access any component logger as follows

static final Logger TEST_LOGGER = Logger.getLogger("test1");

use TEST_LOGGER.debug("any debug message");

By the above approach we can just have a single log4j bundle in the repository and not only avoid issues occuring from static variables but also can take full benefit of log4j API's.

Extending OSGi telnet for custom commands

OSGi telnet command provided by equinox can be easily extended to implement custom commands.

First we need to write a class with which implements the custom commands.the methods should start with _ to be identified as osgi telnet commands.The getHelp command needs to be overwritten ,which will display the command when help is hit on the telnet console.

import org.eclipse.osgi.framework.console.CommandInterpreter;
import org.eclipse.osgi.framework.console.CommandProvider;

public class CustomCommands implements CommandProvider {
public String getHelp() {
return "***********CUSTOM COMMANDS*******************\n";

public void _testcommand(CommandInterpreter ci) {
ci.println("arg 1" + ci.nextArgument());
ci.println("arg 2" + ci.nextArgument());

Next step is to write a BundleActivator and register the command Provider service.

public void start(BundleContext ctx) throws Exception {
customCmd = new CustomCommands();
//created a instance of the implementation of our custom commands
ctx.registerService(CommandProvider.class.getName(),customCmd, null);


Dont forget to add the bundle activator class to the manifest. Manifest should include the following.

Import-Package: org.eclipse.osgi.framework.console;version="[1.0.0,1.0.0]",
Bundle-Activator: com.command.extender.CommandBundleActivator

JMX using Spring

JMX aims to create standard API's for managing and monitoring java applications.

Managing - changing values at runtime.

Monitoring - Reporting certain conditions.

Mbean -is a java bean with a management interface.

Mbean can expose attributes(through getters and setters) or any opertaions.Management interface can be defined statically or at runtime through interfaces.MBean Server acts as a broker between interacting beans or beans and remote clients.

Mbean server maintains a key to all registered means which is called as object name.The default protocol used is RMI , but can be changed to SOAP or Hessian.

Using raw JMX APi's is difficult , spring simplifies this.

Use the following configuration to create a MBeanServer. This will be required normally only if we are running standalone code.Else most of the containers like tomcat or spring dm provide the default MBeanServer which can be used to register the Mbeans.

<bean id="MBeanServer" class="">
<property name="locateExistingServerIfPosssible" value="true">

Configuration to register a bean as MBean to MBeanServer.

<bean id="jmsSample" class=""></bean>

<bean class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<entry key="service:name=jmsSample" value-ref="jmsSample" />

By this all methods and attributes of this can be accesed using jconsole. Sometimes this may not be what we want .we would want to control the set of operations which are visible through JMX.

The Spring MbeanExporter allows the following stratergies

1. ObjectnamingStratergy - this will help in identifying the mbean in the jconsole.

  • a. KeyNamingStratergy(Default) - key passed will become the name
  • b. IdentityNamingStratergy -generates a object name dynamically
  • c. MetaDataNamingStratergy - reads object name from source level meta-data (annotations)

2. MBeanInfoAssembler

When we want to control what we are exposing through JMX this is the better approach

  • SimpleReflectiveMbeanInfoAssembler -Default -Exposes all public methods and properties
  • MethodNameBasedMbeanInfoAssembler Methods can be configured through spring xmls which will be exposed through JMX.
  • MetadataMBeanInfoAssembler what needs to be exposed is controlled using source level annotations.
  • InterfaceBasedMBeanInfoAssembler
a. Using managed Interfaces property

<bean class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<entry key="service:name=jmsSample" value-ref="jmsSample" />
<property name="assembler">
<property name="managedInterfaces">


Here the jmsSample bean need not implement teh managedInterface.

b Using interfaceMapping property

<bean class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<entry key="service:name=jmsSample" value-ref="jmsSample" />
<property name="assembler">
<property name="interfaceMappings">
<entry key="service:name=jmsSampleService" value=""></entry>



Thea bean jmsSample must implement the interface mentioned in interfaceMapping property

This API helps in monitoring application using JMX.

Thursday, November 12, 2009

Spring Training -Day 6

Telnet console 2401 – ssh shell -2402 in DM2 .

2.0 release will have both osgi console and dm shell (osgi console will be disabled by default)

Dm Kernel – lightweight – no web profile.

No plans to support EJB

Bundles in usr directory is not exposing service because – not in active state – need to get some code to move it to active state.

Bundles in pick up move to active state by default.

Import – org.osgi.framework – will not work , as jar is in lib directory .Work Around is to copy paste it into repository/bundles/usr.

Spring dm automatically creates a property for service by name – bean name.

Also application context itself is exposed as service – can be verified with osgi console

Logback – for logging in dm 2.0

In JVM failure - can be achieved using ranking attribute

Load time weaving – more complex when many bundles are there , so hardcoded in DM server - just below boot Classloader (this is not possible with aspectj being a bundle)

Require Bundle(used for Split packages)

Require bundle – all exported packages are imported

Deployment pipeline – Like wars and non osgi headers still works under spring DM because –this is processed by DM server to convert it into osgi complaint bundle - End result is visible in work directory

When Dm server starts all bundles are not seen in osgi console – They move to resolved state , only when required(looking to find required imports) they move to resolved state.

Osgi reference has bean name attribute which can be used as default filter.

Bundles have version , services have ranking – Service ranking is part of OSGi spec

Custom osgi commands – implement Command Provider – equinox specific

2.0 modules – has attribute - sticky for service.

Spring integration

Enterprise Integration Pattern –implementers are SI and Camel

Spring Training -Day 5

Create new platform (may be equinox 3.5) – eclipse may be using 3.4

Eclipse takes ini file – which when bundles added to a folder adds it to the file –Eclipse can do it easily.

Uses conflict may be ClassCastExceptions or Linkage Exceptions

Uses is whatever the bundle is resolved to .(Ex If struts has import;log4j and in any Export blabla;uses log4j – no issues because it will resolves to log4j in applications classpath just forcing us to use the same log4j.. When uses is with version becomes very critical)

Ideally 3rd party guys should not be ideally using uses –unless they want to restrict , but still relaxed using import in struts lib without version – so whatever 3rd party resolves to in our lib.

Import without version no – resolves to latest.

Class loader performance may increase -steps reduced for loading from the conventional model.

Osgi command – packages - searches for the package in all bundles.

BundleContext- used to install/uninstall bundles, deal with events and services programmatically

When multiple services have same ranking – will be solved based on service id – least one – the first one registered.

Extender bundle

Spring extender bundle creates bundle context for bundles which are in ACTIVE state . May be this is the reason bundles in usr lib cannot exposes services.(because they don’t move to active state)

Application context for bundles are created asynchronously when DM server starts up. It can be changed to get a sync behaviour.

When synchronous, it does not spawn a new thread for creating context and waits until context is created.(If any bundle is picked up before by the extender that may run in a separate thread)

Appcontext fails – it uninstalls the bundle – hence cannot verify errors from osgi console.

Service mandatory wait is asynchronous.

Extender Bundle – is like SpringContextLoadListener in web Apps

Extender bundles creates appContext for all bundles which are in ACTIVE state.

Accessing BundleContext – implements BundleContextAware

Either put appcontext file in META-INF / spring or use Spring-Context header in manifest file.

Mandatory Service


Cardinality - 1:1 ,0:1, 0:n,1:n – renamed as availability attribute in Dm 2.0

osgi: set and osgi:list

Consumers can listen to bind-unbind events

Publishers can register to register and unregister events.

RFC 124 – Moving towards component and service than spring specific osgi:service and bean .

Spring Training - Day 4

Spring Security

Principal –User,Device or system that performs action

Authentication –Establishing principals credentials are proper.(LDAP ,Database etc)

Authorization –Deciding if a principal is allowed to perform an action.

Secured Item – resource being secured.

Spring security is Portable across containers.

Secure item – method , web page(url) or flow(web flow)

Voters – 2 default- role based and authenticate based

3 types of AccessDecision manager (judges)

1. AffirmativeBased (anyone says yes –it’s a yes) -Default

2. Unanimous based – very conservative – one voter says no – it’s a no

3. Consensus based – based on majority says yes – majority is configurable – all these are configurable

Configuration in Web Application

<security:http> - configures default accessmgr, default filters, voters, security interceptor etc

Configures a servlet filter in web.xml

<security intercept-url pattern=”…” filters=”” acess=””/> can be configured

Spring security Taglibs since spring 2.0

Method Security(based on AOP)

Xml based - point cuts in xml with access role

Configuration based – have to register to get this enabled. , also has JSR specific annotations

Bad to put security constraints inside class – use xml approach over annotations – security is infrastructure

Advanced Security In web –

HttpSessionContextIntegrationFilter – stores context in session - if exists gets it and binds to thread local –way back binds it to session

LogoutFilter –clears security context on logoff

AuthenticationProcessingFilter - If not authenticated then send to login page

ExceptionTranslationFilter – converts exception into http responses and redirects

FilterSecurityInterceptor - authorises web requests based on url patterns

Any of these can be replaced and any can be added in the required order.

So filters for all these purposes are already placed.

Security context can be obtained anywhere in the code using – spring class SecurityContext.getCtx();

Obfuscating – is just setting bean – to avoid knowing technology

Spring Remoting

Consistency across all protocols and flipping from one protocol to another is simple.

Supported Protocols

HttpInvoker – is a protocol –over http
Hessian/Burlap(for sending XML over HTTP –Less predictable with complex types)

Hessian –uses binary xml
Burlap –uses textual xml

Spring on Server & Client –Use Http Invoker
Java Env but no Web Server –Use RMI
Interop with other languages Using HTTP – Hessian

Spring JMS


Spring JMSTemplate


JMSTemplate – takes connectionFactory,MessageConvertor,DestinationResolver,

Spring JMX

MBean is a standard java bean with an additional management interface – attributes (with getters and setters) and Operations

Rmi is default protocol – can be changed

JVM runs a default MBean server , we can also override this by one given from spring

<context mbean –export>

Default –export everything – mostly a bundle will have only mbeans exposed

Export bean as MBean.

Strategies –

objectNamingStratergy- keyNamingStratergy(Default) , IdetitynamingStratergy(naming by objected from JVM),MetaDataNamingStratergy (annotations) – not recommended

One strategy can be overriden by the other.

MBeanInfoAssembler- by implementations of the MBeanInfoAssembler interface

To run with JMX add as VM param


Single Version mean atleast that version

Resolves to the greatest -

Running in eclipse

Added vm param for clean

In manifest given space for the next line – because its reserved for headers

Import package , not mentioned – binds to the latest

Resolved phase- doesn’t mean classes are loaded

When classloader gets GC’ed - when objects are Gc'ed and all bundles importing from this bundle are refreshed(osgi refresh command)

Using Eclipse to simulate Equinox

Run configurations - > OSGi Configurations – new - Uncheck target platform - In filter search org.eclipse.osgi(any version ) – select it – apply – run

ss will show only equinox bundle.

Change run config as - -Dosgi.clean=true

Create new project – plugin – new plugin project - select run environment as equinox

Can run this new project under equinox with the created run configurations – Run as ...

Saturday, November 7, 2009

Spring Training -Day 3

Transaction Management


Only way to handle transaction is hold on to the same connection –only way of doing it.

JTA – not good , scalability becomes difficult .

Ex: EBay – develop undo behaviour –compensatory action – 3rd part its the only option- for every method need a undo method.

Can use any datasource – no need to tieing it to spring jdbc datasource

Lots of transaction management – datatSourceTransactionMgr,HibernateTransactionMgr,Jps…,Jta..

Connection pool – use apache DBCP or c3p0

<tx:annotation driven> - registering for annotations

<bean id=”transactionManager” class=”…:> … datasource as property </>

transactionManager – should be the name – else have to explicitly mention in the <tx:annotation ……transaction manger=””.>

@Transactional at class level – all public method(because proxy sees only public method) will be transactional

Can have timeout – default is 60 secs

Datasource , transaction – better use xmls – infrastructure components (Aspects annotation are better)

Xml based approach - define transaction mgr, then define transaction interceptor- <tx:advice… > define pointcut

Tx:advice – is just used for overiding , not required

Xml approach advantage - can take these point cut definition from property files.

Set isolation levels – else though not committed , one thread can see the other

For recursive methods with @transaction – the same transaction context will be used.

Transaction Propagation – Propagation.REQUIRES_New – new one transaction context will be created per transaction.

So for iterative ones – if inner @Transaction is marked for required_new ,inner one will be committed irrespective of the other.

Can avoid rollback –with noRollBack option


@Autowired –field level ,method level and constructor level


@Autowired default by Type .-for all auto wired injections including and filed injections.

Test x; though x is name of any bean it will look for type Test.

@Autowired for field injection – Doesnt require setters.

Multiple types or no types will give error.

@Autowired not only for setter – for any method,field,constructor

Autowired for collections – List<Types> - all these types will be autowired into the list.

@Autowired(required=false) – does not fail when no type is found

@Qualifier – filtering when injecting by type – properties have to be mentioned in the bean
[default is name – when no name for bean is mentioned it is taken as id- That is why we say ctx.getBeanByName() and still use id it works]

@Resource –JSR 250 – injection by name – equivalent to ref in xml – not specific to Spring its in JSR 250

@Resource – also for JNDI references

@Component - alternative for writing bean definition in xml can be use with @Scope

@Component can also have bean name-else classname will be taken as bean name with first letter as small letter

<context:component scope> is required to identify components. – no need for annotation config as this is a superset of it.

<context:component scope> - can have filters – includes , excludes etc – without this Component will not work

Component scanner is above annotation processor. – so need to register annotation processor when using component scanner.

@value annotation will work with spring 3.0 – no support in spring 2.5

Both xml and annotation beans - if they have same name xml will override annotations , if the bean names are different 2 instances will be created.


Junit 4 – has annotations

Test runner - @Runwith (SpringJunit4ClassRunner.class)

@ContextConfiguration - with location of appContext.xml

Follow naming convention to avoid giving location - <testcasename>-context.xml

In case we need access to applicationCtx beans write private field and write @Autowired over it.

Name of bean if annotated with @Component –same as class name with first letter as small letter

With map it will put key as bean name when autowired.

@autowire with qualifier is very useful

Stubs and Mocks are different

Mock libraries - EasyMock,Jmock ,Mokito


Example with mockito – works by proxy- how to ensure method is called n number of times

During db tests – data inserted is automatically deleted , default can override if required.


Web Layer should be very thin layer speaking to the backend service layer.

Spring Web Flow - Same url will be used , server maintains a state based on which flow will continue.

ContextLoadListener in web.xml - Root ApplicatonContext

WebApplicationContextLoader - register in servletContext – For WebApplicationContext

Using DispatcherServlet

2 contexts , RootApplicationContext and WebApplicationContext.

Web (DispatcherServlet) context can rootContext but not the other way round.

Spring MVC – annotation suited

WebApplicationContextUtils – static helper for accessing spring beans in web context.

Processing Flow -> Request -> Dispatcher Servlet -> Handler (Controller) -> Result View(send to DispatcherServlet) -> View

@Controller- equivalent to struts actions classes but can have multiple mapping for different url’s per method inside it.

@RequestMapping -for mapng urls

@RequestParam – mapping fields from HttpRequest.

Controller returns View name – default is path to jsp page

If controller returns null – then default view based on request url.

DispatcherServlet delegates to viewResolver to map returned view names to view implementations.

Default View resolver treats view name as Web –App relative path.

View Resolver – can take prefix and suffix as params.

If returned as string from handler – its taken as a view name

Spring Training -Day 2

Bean name will be generated by bean id. Context.getBean(name) hence works by id.

Writing custom annotation – write custom annotation and register pre-processor to add custom logic to it.

BeanPostProcessor- deals with objects – postInit & preInit

Interceptor- aspect with single advice[will be called when bean is created]

isSingleton method inside factory will be called only once if isSingletonMethod() set to true –Doesn’t make sense if factory itself is prototype

Inheritance – bean can be marked as

abstract=true - instance wont be created

Parent – parent=”” – for overriding

PropertyEditors- how properties are converted in xmls which always are mentioned as string ex – toDate,Integer etc –Spring has many of its own

We can register our own propertyeditors - For any type –call our propertyEditor – this is not like set of interceptors instead editor is picked from a map.

Following conventions - put customEditor in same package as code , and name should be <type>+Editor - no need to explicitly register the editor.

Import configuration file - <import resource=”ddsdsd.xml” />

P namespace – allows properties to be set as attributes in bean definition.

Util namespace – loading properties – diff from propertyplaceholder – util :properties , set,list,Map,reading constants


2 technologies

Spring Aop – Runtime –Using Dynamic Proxy

AspectJ- Compile Time OR Load Time –byte code injection

Performance – aspectj build time is best but complex.

For AspectJ :;jsessionid=E64F684641DCF76CEC10633EFF108059

Spring Aop – uses (hides this complexity)

a. uses JDK dynamic proxy when interface is mentioned


Method invocations on an instance of a dynamic proxy class are dispatched to a single method in the instance's invocation handler, and they are encoded with a java.lang.reflect.Method object identifying the method that was invoked and an array of type Object containing the arguments.

b. uses CGlib when no interface is mentioned

CGLIb can be forced in both cases using Proxy-target-class=false in definition.

Creating proxy using APIs - org.springframework.aop.framework.ProxyFactory;

Can add advice to the proxy – which recognizes either annotations or anything else

Adding aspectj weaving adds a context weaving classloader

Hierarchy --- BootClassLoader,Aop Context weaving Classloader,Extension loader,Application loader

The above happens for only Aspectj Based viewing

Hence all classes other than in boot path can be intercepted.

Delegation Of Classloader – first goes to parent if class def is not found and then comes down

When using jdk dynamic proxy –cast to interfaces

CGlib works by extending the class definition and then creating instance of that , old object is GC’ed.

Hence with final classes it throws error

Constructor gets called twice.- because extended.

Internal methods don’t get called.

JdkDynamic uses the same instance

JointPoint- execution context

PointCut - Expression


Aspect- class

Advice -@Before,@Afterreturning,@AfterThrowing,@After,@Around

Spring JDBC

No checked exception – all run time exceptions –rarely Db exceptions are recoverable

Callback pattern – give ur reference to some to call u at right times

Does from Getting connections, Participating in Transaction, Execution of statement, Processing ResultSet, Handling Exceptions, Closing connection.

Need to provide a datasource along with transactionManager. – Datasource manages the connection pooling

We can use Apache DBCP or C3po for pooling.

JdBCTemplate methos like queryForMap,queryForList

RowMapper – Each Row maps to a Doman Object
RowCallBackHandler – No return value
ResultSetExtractor - Multiple rows map to a single object.

Spring handles all exceptions irrespective of the vendor. It keeps a internal mapping of all error codes specific to the vendor, and gives very descriptive errors.

Spring Training -Day 1

Trainer :

Spring deals with plumbing so that we can focus on domain problem.

We analyse what part Is business logic & what’s rest ?

Creation pattern - Strategy Pattern – Dependency Injection – Interface based.

Conventions over configuration – ex maven etc

Annotations – when dependency is mostly static , and also confusion can be solved using conventions.

Generic at compile time Vs runtime – This may be to support old Java runtimes

Implement FactoryBean – the getObject() – will give result whenever the bean is injected.

How to get factory itself - &<beanname> in property field.

FilePathXmlContex(“classpath:dhgadhs.xml”,c:/sdsd/sdsd/asds.xml); - classpath will ensure its searched in classpath for the first xml

Bean Life Cycle

BeanFactoryPostProcessor – just after dependency tree is constructed but before objects are created.Can change definition of any bean here.

One usecase would be propertyplaceholderconfigurer – to replace values with exact properties from file.

once configurer like placeholder is register it will be replaced with property files. - <context:property placeholder/>

<context:annotation-config/> - needs to be registered for annotations.

@Required - throws error if property is not set

Enforcing init method – by implementing initializingBean

Proxy – Decorator pattern

<bean class=”Org.springframework.beasn.factory.config.PropertyPlaceholderConfigurer” >

<property name=”location” value”…”/>


With namespace – no need to remember the class

<context:property-placeholder location=””/>

Giving class as part of application context – helps identify where the xml is located

Bean Initilization (3 ways)

@PostConstruct ,init-method,implement interface initializingBean

Bean Post processor example - @Required – have to add contextannotation config

Destroying the application Context


Bean Destruction(3 ways)

@PreDestory,destroy-method,implement interface DisposableBean

Scopes – request and session makes sense only when they are in a web continer.

Issues with loading Native libraries in OSGi Bundles

The Java virtual machine (JVM) allows only one class loader to load a particular native library.
(which means two bundle cannot load same native library)

There is no application programming interface (API) to unload a native library from a class loader.

Native libraries are unloaded by the JVM when the class loader that found the library is collected from the heap during garbage collection.

If a shared library that is configured with a native library path is associated with an application, whenever the application is restarted or dynamically reloaded the application might fail with an UnsatisfiedLinkError indicating that the library is already loaded. The error occurs because, when the application restarts, it invokes the shared library class to reload the native library. The native library, however, is still loaded in memory because the application class loader which previously loaded the native library has not yet been garbage collected.

A native library is unloaded only when the class loader that loaded it has been garbage collected. When a bundle is uninstalled or updated, any native libraries loaded by the
bundle remain in memory until the bundle's class loader is garbage collected. The garbage collection will not happen until all references to objects in the bundle have been garbage collected, and all bundles importing packages from the updated or uninstalled bundle are refreshed. This implies that native libraries loaded from the system class loader always remain in memory because the system class loader is never garbage collected

Spring forum :

Solution – load this library in a bundle which won’t be refreshed or set a flag which shoudl be checked when reloading any bundle.

The option of changing native code name may result in memory leaks, because multiple native code accumulate in the process space.

Only the JVM class loader can load a dependent native library.

For example, if NativeLib1 is dependent on NativeLib2, then NativeLib2 must be visible to the JVM class loader. The path containing NativeLib2 must be specified on Java library path defined by the LIBPATH environment variable.

If a native library configured in a shared library is dependent on other native libraries, the dependent libraries must be configured on the LIBPATH of the JVM hosting the application server in order for that library to load successfully.


Garbage Collection - Log Analysis

25646.328 :[GC 325407K->83000K(776768K), 0.2300771 secs]
25646.328 : [GC 325816K->83372K(776768K), 0.2454258 secs]
25646.328 : [Full GC 267628K->83769K(776768K), 1.8479984 secs]

25646.328 –time since JVM started

325407K->83000K :combined size of live objects before and after garbage collection
After minor collections the count includes objects that aren't necessarily alive but can't be reclaimed, either because they are directly alive, or because they are within or referenced from the tenured generation.

(776768K) -> is the total available space, not counting the space in the permanent generation, which is the total heap minus one of the survivor spaces

0.2300771 secs –time taken

Here we see two minor collections and one major one.

Good Link:

Sample GC logs:
25646.328: [GC [PSYoungGen: 53934K->1783K(55744K)] 139043K->86893K(521792K), 0.0091130 secs] [Times: user=0.02 sys=0.01, real=0.01 secs]
25650.658: [GC [PSYoungGen: 55735K->2232K(54208K)] 140845K->91675K(520256K), 0.0140890 secs] [Times: user=0.06 sys=0.00, real=0.02 secs]
[2009-11-03 10:02:23.092] fs-watcher Processing 'DELETED' event for file 'xxx.jar'. ? Application Undeployed
[2009-11-03 10:02:24.495] fs-watcher Undeployment of ‘xxx' version '0' completed.
[2009-11-03 10:02:48.592] fs-watcher Processing 'CREATED' event for file 'xxx.jar'.
[2009-11-03 10:02:52.915] fs-watcher Deployment of 'xxx' version '0' completed.
25705.888: [Full GC (System) [PSYoungGen: 416K->0K(53632K)] [PSOldGen: 122447K->122819K(466048K)] 122863K->122819K(519680K) [PSPermGen: 56927K->56927K(58496K)], 0.4994360 secs] [Times: user=0.50 sys=0.00, real=0.49 secs]
Total time for which application threads were stopped: 0.5127720 seconds

Approx 2.20 mins later after the redeployment the memory in OldGen starts piling up

33705.323: [Full GC (System) [PSYoungGen: 3584K->0K(51328K)]
[PSOldGen: 162686K->166028K(466048K)]
[PSPermGen: 61486K->61486K(61824K)], 0.6978710 secs]
[Times: user=0.70 sys=0.00, real=0.70 secs]

33766.045: [Full GC (System)[Unloading class sun.reflect.GeneratedSerializationConstructorAccessor305]
[Unloading class sun.reflect.GeneratedSerializationConstructorAccessor306]
[PSYoungGen: 3424K->0K(51456K)] [PSOldGen: 175451K->178649K(466048K)] 178875K->178649K(517504K) [PSPermGen: 61487K->61487K(61824K)], 0.7389690 secs] [Times: user=0.73 sys=0.01, real=0.74 secs]
36459.779: [Full GC [PSYoungGen: 41152K->0K(57664K)] [PSOldGen: 554317K->557726K(699072K)] 595469K->557726K(756736K) [PSPermGen: 61442K->61442K(61824K)], 1.6296560 secs] [Times: user=1.62 sys=0.00, real=1.63 secs]
Total time for which application threads were stopped: 1.6310400 seconds
Total time for which application threads were stopped: 0.0011620 seconds

After approx 3hrs 40mins after the redeployment, application starts doing Full GC every 2 secs virtually unable to collect anything. The GC pause times are 2secs. So application is not
running at this point.

38208.203: [Full GC [PSYoungGen: 42047K->40198K(53952K)]
[PSOldGen: 699068K->699068K(699072K)]
[PSPermGen: 61376K->61376K(61568K)], 2.1202220 secs]

[Times: user=2.16 sys=0.00, real=2.13 secs]
Total time for which application threads were stopped: 2.1220930 seconds
38210.406: [Full GC [PSYoungGen: 42048K->38287K(53952K)] [PSOldGen: 699068K->699072K(699072K)] 741116K->737359K(753024K) [PSPermGen: 61376K->61369K(61568K)], 2.2874650 secs] [Times: user=2.28 sys=0.00, real=2.28 secs]
Total time for which application threads were stopped: 2.2889430 seconds
38213.678: [Full GC [PSYoungGen: 42043K->40523K(53952K)] [PSOldGen: 699072K->699072K(699072K)] 741115K->739595K(753024K) [PSPermGen: 61369K->61369K(61568K)], 2.1083830 secs] [Times: user=2.11 sys=0.01, real=2.11 secs]
756 MB -Xmx

Ref :

Each blue box represents a collector that is used to collect a generation. The young generation is collected by the blue boxes in the yellow region and the tenured generation is collected by the blue boxes in the gray region.

  • "Serial" is a stop-the-world, copying collector which uses a single GC thread.
  • "ParNew" is a stop-the-world, copying collector which uses multiple GC threads. It differs from "Parallel Scavenge" in that it has enhancements that make it usable with CMS. For example, "ParNew" does the synchronization needed so that it can run during the concurrent phases of CMS.
  • "Parallel Scavenge" is a stop-the-world, copying collector which uses multiple GC threads.
  • "Serial Old" is a stop-the-world, mark-sweep-compact collector that uses a single GC thread.
  • "CMS" is a mostly concurrent, low-pause collector.
  • "Parallel Old" is a compacting collector that uses multiple GC threads.

    Using the -XX flags for our collectors for jdk6,

  • UseSerialGC is "Serial" + "Serial Old"
  • UseParNewGC is "ParNew" + "Serial Old"
  • UseConcMarkSweepGC is "ParNew" + "CMS" + "Serial Old". "CMS" is used most of the time to collect the tenured generation. "Serial Old" is used when a concurrent mode failure occurs.
  • UseParallelGC is "Parallel Scavenge" + "Serial Old"
  • UseParallelOldGC is "Parallel Scavenge" + "Parallel Old"

  • Ref :

    These 2 references clears most of teh doubts pertaining to jvm internals and gc tuning.

    Free Domain Names @!