Wednesday, September 30, 2009

Why Enum in Java

If you use Java1.5, there is a feature declaring constant value i.e Enum. An Enumerated type defines a finite set of symbolic names and their values. These symbolic names are called enum constants or named constants.

Well, you can declared such constants by static final variable like:


public class MyConstants
{
public static final int BUSY = 1;
public static final int IDLE = 2;
public static final int BLOCKED = 3;
}


such constants are not typesafe, as any int value can be used where we need to use a constant declared in the MyConstants class. Such a constant must be qualified by the class name. When such a constant is printed, only its value is printed, but we unable to print its name. One important thing is that, if you want to modify the value of any constant, then you have to compile both, the class or interface that declare the constant and the class where this constants are used. This is required bkz, constant names are substituted by its value at compile time.

Please look the code Snippet for the approach outlined above.

public enum ConstantEnum {
BUSY(3),IDLE(2);

int data;
private ConstantEnum(int refValue) {
data = refValue;
}

public int getValue()
{
return data;
}
}

public class TestValue {
public static void main(String arg[])
{
int i= ConstantEnum.BUSY.getValue();
System.out.println("using Enum value :"+ConstantEnum.BUSY);
System.out.println("using static final :"+MyConstants.BUSY);
}
}

Friday, September 18, 2009

Data Access using JDBC in Spring Framework

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.

Thursday, September 17, 2009

DAO Support in Spring Framework

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.

Saturday, September 12, 2009

Dependency Lookup in Spring using Properties file

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

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

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

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();
}
}