Archive for the ‘Spring Framework’ Category

Data Access using JDBC in Spring Framework

September 18, 2009

JDBC support provided by Spring is consist of four different packages core, datasource, object and support.

The org.springframework.jdbc.core package contains the JdbcTemplate class and its various callback interfaces, plus a variety of related classes.

The org.springframework.jdbc.datasource package contains a utility class for easy DataSource access, and various simple DataSource implementations. The utility class provides static methods to obtain connections from JNDI and to close connections if necessary. It has support for thread-bound connections, e.g. for use with DataSourceTransactionManager.

the org.springframework.jdbc.object package contains classes that represent RDBMS queries,updates, and stored procedures as thread safe, reusable objects.

the org.springframework.jdbc.support package is where you find the SQLException translation functionality and some utility classes.

Advertisements

DAO Support in Spring Framework

September 17, 2009

Today, there are no of Data Access technologies available such as JDBC, JDO, Hibernate and JPA etc. If we talk about Spring framework, Spring supports almost all type of Data Access Technologies in a consistent way. The important thing is that, Spring Allows to switch between any Data Access Technology without worrying about Exceptions handling for a particular data-access technology.

Spring provides no. of abstract classes for DAO Support. These abstract classes have methods for providing the data source and any other configuration settings that are specific to the relevant data-access technology.

• JdbcDaoSupport – superclass for JDBC data access objects. Requires a DataSource to be provided; in turn, this class provides a JdbcTemplate instance initialized from the supplied DataSource to subclasses.

• HibernateDaoSupport – superclass for Hibernate data access objects. Requires a SessionFactory to be provided; in turn, this class provides a HibernateTemplate instance initialized from the supplied SessionFactory to subclasses. Can alternatively be initialized directly via a HibernateTemplate, to reuse the latters settings like SessionFactory, flush mode, exception translator, and so forth.

• JdoDaoSupport – super class for JDO data access objects. Requires a PersistenceManagerFactory to be provided; in turn, this class provides a JdoTemplate instance initialized from the supplied PersistenceManagerFactory to subclasses.

• JpaDaoSupport – super class for JPA data access objects. Requires a EntityManagerFactory to be provided; in turn, this class provides a JpaTemplate instance initialized from the supplied EntityManagerFactory to subclasses.

Using DAO in Spring Framework

September 13, 2009

Using Single Data Source in Spring

September 13, 2009

Dependency Lookup in Spring using Properties file

September 12, 2009

File Name: property-class.properties

message.(class) = MessageServiceImpl
defaultMessage.(class) = DefaultMessageService
defaultMessage.service(ref) = message

File Name: DependencyLookupFromProp.java

Loading Class from Spring property file

September 12, 2009

File Name: property-class.properties

message.(class) = Message

File Name: LoadClassFromProp.java

import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;

public class LoadClassFromProp {

public static void main(String[] args) {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
BeanDefinitionReader reader = new PropertiesBeanDefinitionReader(factory);
reader.loadBeanDefinitions(new ClassPathResource(“property-class.properties”));
Message msg = (Message) factory.getBean(“message”);
System.out.println(msg.getMessage());
msg.setMessage(“Good Afternoon”);
System.out.println(msg.getMessage());
}

}

class Message
{
private String message = “”;
public Message() {
message = “Good Morning..”;
}

public void setMessage(String msg)
{
this.message = msg;
}

public String getMessage()
{
return this.message;
}
}

What are different Spring Contexts

September 12, 2009

ApplicationContext
Central interface to provide configuration for an application. This is read-only while the application is running, but may be reloaded if the implementation supports this.

An ApplicationContext provides:
• Bean factory methods for accessing application components. Inherited from ListableBeanFactory.
• The ability to load file resources in a generic fashion. Inherited from the ResourceLoader interface.
• The ability to publish events to registered listeners. Inherited from the ApplicationEventPublisher interface.
• The ability to resolve messages, supporting internationalization. Inherited from the MessageSource interface.
• Inheritance from a parent context. Definitions in a descendant context will always take priority. This means, for example, that a single parent context can be used by an entire web application, while each servlet has its own child context that is independent of that of any other servlet.

In addition to standard BeanFactory lifecycle capabilities, ApplicationContext implementations detect and invoke ApplicationContextAware beans as well as ResourceLoaderAware, ApplicationEventPublisherAware and MessageSourceAware beans.

FileSystemXmlApplicationContext
Standalone XML application context, taking the context definition files from the file system or from URLs, interpreting plain paths as relative file system locations (e.g. “mydir/myfile.txt”).

NOTE: Plain paths will always be interpreted as relative to the current VM working directory, even if they start with a slash. (This is consistent with the semantics in a Servlet container.) Use an explicit “file:” prefix to enforce an absolute file path.

Note: In case of multiple config locations, later bean definitions will override ones defined in earlier loaded files. This can be leveraged to deliberately override certain bean definitions via an extra XML file.

ClassPathXmlApplicationContext
Standalone XML application context, taking the context definition files from the class path, interpreting plain paths as class path resource names that include the package path (e.g. “mypackage/myresource.txt”).

The config location defaults can be overridden via getConfigLocations(), Config locations can either denote concrete files like “/myfiles/context.xml”.

Note: In case of multiple config locations, later bean definitions will override ones defined in earlier loaded files. This can be leveraged to deliberately override certain bean definitions via an extra XML file.

AbstractApplicationContext
Abstract implementation of the ApplicationContext interface. Doesn’t mandate the type of storage used for configuration; simply implements common context functionality. Uses the Template Method design pattern, requiring concrete subclasses to implement abstract methods.

In contrast to a plain BeanFactory, an ApplicationContext is supposed to detect special beans defined in its internal bean factory: Therefore, this class automatically registers BeanFactoryPostProcessors, BeanPostProcessors and ApplicationListeners which are defined as beans in the context.

AbstractRefreshableApplicationContext
Base class for ApplicationContext implementations which are supposed to support multiple refreshs, creating a new internal bean factory instance every time. Typically (but not necessarily), such a context will be driven by a set of config locations to load bean definitions from.

The only method to be implemented by subclasses is loadBeanDefinitions(org.springframework.beans.factory.support.DefaultListableBeanFactory), which gets invoked on each refresh. A concrete implementation is supposed to load bean definitions into the given DefaultListableBeanFactory, typically delegating to one or more specific bean definition readers.

AbstractXmlApplicationContext

ConfigurableWebApplicationContext

GenericApplicationContext

GenericWebApplicationContext

StaticApplicationContext

StaticWebApplicationContext

XmlWebApplicationContext

Spring Bean Dependency

September 12, 2009

File Name: dependency.xml

File Name: Dependency.java


import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;


public class Dependency {
public static void main(String[] args) {
XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("dependency.xml"));

B b = (B) bf.getBean("b");
A a = (A) bf.getBean("a");
System.out.println(a);
System.out.println(b);
}
}

final class Shared {
private static Object value = null;
private Shared() {

}

public synchronized static void setValue(Object o) {
value = o;
}

public static Object getValue() {
return value;
}
}

class A
{
public A()
{
Shared.setValue("Undetermined");
}

@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("A");
sb.append("{}");
sb.append("Shared.getValue()=").append(Shared.getValue()).append("}");
return sb.toString();
}
}

class B
{
public B()
{
Shared.setValue("Completed");
}

@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("B");
sb.append("{}");
sb.append("Shared.getValue()=").append(Shared.getValue()).append("}");
return sb.toString();
}
}

What is IoC Container

August 28, 2009

The business logic layer can be developed without coupling it with any other layers by using IoC provided by the Spring Framework. The IoC container is the core component of the framework. IoC lets the developer implement the business logic as Plain Old Java Objects (POJO) and wire them up so that they can be injected or called at runtime. This approach lets you avoid specifying the business objects as dependencies at compile time.

What is IoC

August 28, 2009

IoC stands for Inversion-of-Control. IoC is a concept,and an associated set of programming techniques, in which the control flow is inverted compared to the traditional approach. “In other words, the framework calls the procedures created by the programmer, rather than programmer calling the procedures or methods of the framework. IoC is based on the “Hollywood Principle.” The Hollywood Principle says “Don’t call me, I will call you.”

IoC is used to ‘inject’ dependencies at runtime. When one uses this pattern, the dependencies of a particular object are not satisfied at compile time. Instead, the framework provides the required dependencies to the object at runtime. Thus, this pattern releases the programmer from the chore of providing all the dependencies at compile time.