Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Monday, December 31, 2012

Difference between @Autowire and @Resource

1. @Resource is part of JSR-250. @Autowire is part of Spring framework.
2. @Resource can inject by name only(to inject into a field named "xyz" look for a bean named "xyz"). @Autowire can inject by name, type(to inject into a field/parameter of type "Abc", look for a unique bean of type "Abc") and many more.
3. @Resource can inject into a field only. @Autowire can inject into field, constructor and method parameters.
3. @Resource can inject List, Map and other Collection types. @Autowire cannot.

Sources: [1] [2]

Saturday, October 08, 2011

3 ways to initialize and destroy Spring beans

There are 3 ways to initialize (and destroy) spring beans
1. Using init-method and destroy-method attributes
2. Implementing InitializingBean and DisposableBean interfaces
3. Using @PostConstruct and @PreDestroy Annotations (available only in Spring >=2.5)


1. Using init-method and destroy-method attributes
Certain bean methods can designated as initializing and destroying methods using the init-method and destroy-method attributes. Like so:



<bean
    id="studentService"
    class="initMethod.StudentServiceImpl"
    init-method="subscribe"
    destroy-method="unsubscribe"/>



2. Implementing InitializingBean and DisposableBean interfaces
The bean can implement these methods InitializingBean.afterPropertiesSet() and DisposableBean.destroy(). Like so:

public class StudentServiceImpl implements StudentService, InitializingBean, DisposableBean {
    @Override
    public boolean isExists(long studentId) {
        // A fake implementation
        if ( studentId % 2 == 0 )
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception 
    {
        // subscribe logic goes here
    }

    @Override
    public void destroy() throws Exception 
    {
       // unsubscribe logic goes here
    }
}



3. Using @PostConstruct and @PreDestroy Annotations
Note that both of these are JSR-250 annotations (here is a nice introduction to JSR-250 support introduced in spring 2.5).

@PostConstruct
public void subscribe()
{
  // subscribe logic goes here
}


@PreDestroy
public void unsubscribe()
{
  // unsubscribe logic goes here
}

Friday, September 02, 2011

Tuesday, February 08, 2011

Simple Spring bean configuration

Singular property

Simple property

Class Singer implements Performer

{

private String name;

public Singer(String n)

{

this.name = n;

}

}

<bean

id=”xyz”

class=”com.Singer”>

<constructor-arg

value=”xyz”/>

</bean>

Class Singer implements Performer

{

private String name;

public void setName(String n)

{

this.name = n;

}

}

<bean

id=”xyz”

class=”com.Singer”>

<property

name=”name”

value=”xyz”/>

</bean>

Property referencing another bean

Class Drummer implements Performer

{

private Drum drum;

public Drummer(Drum d)

{

this.drum = d;

}

}

<!-- Tabla implements Drum -->

<bean

id=”tabla”

class=”com.Tabla”>

</bean>

<bean

id=”xyz”

class=”com.Drummer”>

<constructor-arg

ref=”tabla”/>

</bean>


OR


<bean

id=”xyz”

class=”com.Drummer”>

<constructor-arg>

<!-- nested bean -->

<bean

class=”com.Tabla”>

</constructor-arg>

</bean>



Class Drummer implements Performer

{

private Drum drum;

public void setDrum(Drum d)

{

this.drum = d;

}

}

<!-- Tabla implements Drum -->

<bean

id=”tabla”

class=”com.Tabla”>

</bean>

<bean

id=”xyz”

class=”com.Drummer”>

<property

name=”drum”

ref=”tabla”/>

</bean>


OR


<bean

id=”xyz”

class=”com.Drummer”>

<property

name=”drum”>


<!-- nested bean -->

<bean

class=”com.Tabla”>

</property>

</bean>

Plural Property

Collections



Class Drummer implements Performer

{



// REFERENCE TYPE

private Collection<Drum> drums;

OR

private List<Drum> drums;

OR

private Set<Drum> drums;

public setDrums(

Collection<Drum> drums)

{

this.drums = drums;

}






// SIMPLE TYPE

private Collection<String> names;

public setNames(Coll... names)

{

this.names = names;

}

}

<bean id=”drum1” … />

<bean id=”drum2” … />

<bean

id=”xyz”

class=”com.Drummer”>


<!-- REFERENCE TYPE -->

<property

name=”drums”>

<list or set>

<ref bean=”drum1” />

<ref bean=”drum2” />

<bean

class=”com.ADrum”/>

<null />

</list or set>

</property>


<!-- SIMPLE TYPE -->

<property

name=”names”>

<list or set>

<value>Name1</value>

<value>Name2</value>

<null />

</list or set>

</property>

</bean>

Name value pairs



Class Drummer implements Performer

{


// Key and values are objects

private Map<String, Drum> drums;

public setDrums(Map... drums)

{

this.drums = drums;

}








// key & values are strings

private Properties notes;

public setNotes(Properties note)

{

this.notes = note;

}

}

<bean id=”drum1” … />

<bean id=”drum2” … />

<bean

id=”xyz”

class=”com.Drummer”>


<property

name=”drums”>

<map>

<entry

key or key-ref=”drum1”

value or value-ref=”drum1”/>

<entry

key=”drum2”

value-ref=”drum2”/>

</map>

</property>

<property

name=”notes”>

<prop

key=”Note1”>

lala

</prop>

<prop

key=”Note21”>

lolo

</prop>

</property>

</bean>

Thursday, October 15, 2009

Nice AOP articles

Spring Terminology: Weaving

Weaving is the process of applying Aspects to Targets to create Proxies. The aspects are woven into the target at the specified joinpoints. This process can happen at different stages of the Target's life
1. Compile Time: Aspects woven into targets when target class is compiled. This requires a special compiler though. Aspectj's weaving compiler weaves aspect this way.
2. Classload time: Aspects woven into targets when target class is loaded into the JVM. This requires a special class loader that enhances the target class's byte code before it is introduced to the application. Aspectj 5's load time weaving (LTW) support is based on this approach.
3. Runtime: Aspects woven into targets when target class is invoked. Typically an AOP container will generate a proxy object that will deliver the aspect functionality before or after delegating to the target object. This is how Spring AOP aspects are woven.

Source: My understanding from reading "Spring In Action"

Spring Terminology: Proxy

When an advice is applied to a Target, it becomes a Proxy. To the clients of the Target, the Target (Pre-AOP) and the Proxy (Post-AOP) are the same. There are no differences in the public APIs exposed by both of the objects. The Delta between the proxy and the target is the implementation to address cross-cutting concerns that are hosted in the Advice.

Source: My understanding from reading "Spring In Action"

Spring Terminology: Target

A target is the object that is being advised. This could be a third party object and a self-written home-grown object. If there was no AOP then then object would handle both its primary logic and cross cutting concern. With AOP this object's responsibility is restored to its code logic and it does not know that it is being advised.

Source: My understanding from reading "Spring In Action"

Spring Terminology: Introductiion

Introduction gives new behavior and state to existing classes without having to change the existing classes. This is achieved by adding new methods and properties to existing classes.


Source: My understanding from reading "Spring In Action"

Wednesday, October 14, 2009

Spring terminology: Aspect revisited

See previous post titled “What is Cross Cutting Concern? Why AOP? What is Aspect?” before reading this.

 

An Aspect is an amalgam/merger of advice (what and when) and pointcuts (where) [see previous posts on advice and pointcuts].

 

 

Spring Terminology: PointCut

An Aspect (see previous post on what an Aspect is) need not handle all Join points of an application. A specific Aspect can be made responsible for a subset of Join points. PointCuts are used to define the subset of join points that a given Aspect is responsible for handling. In other words PointCuts defines the join points where the aspect logic is to be applied. This “where” can be defined on specific, explicit class and method names or through regular expressions that apply to classes and method names that match the pattern.  

Spring Terminology: Join Point

Points in application logic where the aspect’s (see previous posts on what an Aspect is) functionality is to be applied or plugged in. This point could be a method invocation, field write/modification or exception thrown. There are points where the aspect’s logic can be pluged in to add new behaviour.

Spring Terminology: Advice

Defines the responsibility of the Aspect (see previous posts on what an Aspect is) in terms of what (will be performed) and when (it will be performed – before/after/before and after/only on exception).

What is Cross Cutting Concern? Why AOP? What is Aspect?

There are certain aspects of the application that has to be addressed at every layer of the application and cannot be categorized to be a responsibility of any one single layer. Examples are logging, transaction management, security, Caching, Validation etc…

These aspects that span across the several layers of the application are cross cutting concerns. AOP helps decouple cross cutting concerns from the application logic that they impact.

If there was no AOP, one would have to implement common functionality in a base class and have all classes make use it. But this will make the object hierarchy brittle. Other common approach is to delegate common functionality is to utility class. But this will require calls to the utility method spread all across application logic code.



In AOP, the common functionality is implemented in a single class. But this class is invoked by declaratively defining how and where the functionality needs to be applied without having to modify the class to which the functionality is applied to.


These classes that hold common functionality are called Aspects.


Now, the application logic code or service modules contain code pertaining only to their primary responsibility or primary concern and secondary concerns move to aspects. The second advantage is that all common functionality is nicely held in a single place.


Why Dependency Injections

Dependency Injections helps decouple the various components of the application by

  1. Having the components reference each other through abstract interfaces and
  2. Delegate instantiation of concrete implementation classes to a dependency injection framework like Spring