How to inject prototype dependency in a singleton bean


As we know once the singleton bean is created all the properties object defined in it are created once. But what about special and rare case in which one of the property object needs to be created everytime the singleton object is required. for example i have put a property in a singleton object as Timestamp, which can tell me when my singleton object was accessed. For this I need to know the exact time when the object is fetched and not created.
Possible solution could be everytime the method “getInstance()” is called a new Timestamp object is created and injected into spring object.
This is also possible in Spring using look-up method injection.
Lookup method injection refers to the ability of the container to override methods on container managed beans, to return the result of looking up another named bean in the container. The lookup will typically be of a prototype bean.

public abstract class SingletonBean{
public abstract Timestamp getCurrentTime();
}


In spring.xml
< bean id="mySingleton" class="com.SingletonBean" >
< lookup-method name="getCurrentTime" bean="currentTimeBean"/ >
< / bean >
< bean id ="currentTimeBean" class="java.sql.TimeStamp" scope="prototype"/ >

It is mandatory to make currentTimeBean as prototype otherwise same instance of bean will be passed.

Advertisements

What is difference between == and equals() in java?


== operator is used to compare the references of the objects.

public boolean equals(Object o) is the method provided by the Object class. The default implementation uses ==
operator to compare two objects.

But since the method can be overridden like for String class. equals() method can be used to compare the values of two
objects.

String str1 = new String("MyName");
String str2 = new String("MyName");

if(str1 == str2){
System.out.println(“Objects are equal”)
}else{
System.out.println(“Objects are not equal”)
}

if(str1.equals(str2)){
System.out.println(“Objects are equal”)
}else{
System.out.println(“Objects are not equal”)
}

Output:
Objects are not equal
Objects are equal

Lets look at other snippet:

String str2 = "MyName";
String str3 = str2;

if(str2 == str3){
System.out.println(“Objects are equal”)
}else{
System.out.println(“Objects are not equal”)
}

if(str3.equals(str2)){
System.out.println(“Objects are equal”)
}else{
System.out.println(“Objects are not equal”)
}

Objects are equal
Objects are equal

Can a static block throw exception?


Yes, static block can throw only Runtime exception or can use a try-catch block to catch checked exception.
Typically scenario will be if JDBC connection is created in static block and it fails then exception can be caught, logged and application can exit. If System.exit() is not done, then application may continue and next time if the class is referred JVM will throw NoClassDefFounderror since the class was not loaded by the Classloader.

how to access properties file in Spring


PropertyPlaceHolderConfigurer A property resource configurer that resolves placeholders in bean property values of context definitions. It pulls values from a properties file into bean definitions.

The default placeholder syntax follows the Ant / Log4J / JSP EL style: ‘$’

PropertyOverrideConfigurer A property resource configurer that overrides bean property values in an application context definition. It pushes values from a properties file into bean definitions
Example:
A simple class of which values are set from property file.

public class MyBean {

private String myName;
private String password;
/**
* @param args
*/
public static void main(String[] args) {

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("mybean.xml");
MyBean bean = (MyBean)ctx.getBean("myBean");
// getting the properties from the property file
System.out.println(bean.getMyName());
System.out.println(bean.getPassword());
}
public String getMyName() {
return myName;
}
public void setMyName(String myName) {
this.myName = myName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

}

The xml file config

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
default-lazy-init="true">

<bean id="configProperties"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>config.properties</value>
</list>
</property>
</bean>

<bean id="myBean" class="test.tetst.MyBean">
<property name="myName" value="${myname}" />
<property name="password" value="${password}" />
</bean>
</beans>

config.properties files
myname=testing
password=password

Can an Innerclass be instantiated in Spring?


Dont be surprise but the answer is yes..

package com.src;
public class MyClass{
public static class InnerClass{
}
}

In spring.xml it Innerclass can be instantiated as:

< bean id="myclass" class="com.src.MyClass$InnerClass">

Wow !! this is good , spring is amazing.The innerclass should be public and static only.
But i am wondering ,will  there be any real significance left of InnerClass or not?

How to acheive concurrency in Hiberante ?


Consider a scenario in which multiple applications are accessing same database. It is likely that is a data or row is fetched by an application1 and
later on by application2 and application2 makes an update in DB and when application1 makes update then if finds that the old data is lost and not sure what
to do.
To maintain high concurrency and high scalability hibernate allows the concept of versioning.Version checking uses version numbers, or timestamps, to detect conflicting updates (and to prevent lost updates). Hibernate provides for three possible approaches to writing application
code that uses optimistic concurrency.
1) Application version checking: each interaction with the database occurs in a new Session and the developer is responsible for reloading all persistent instances from the database before manipulating them. This approach forces the application to carry out its own version checking to ensure conversation transaction isolation.
This approach is the least efficient in terms of database access.
// foo is an instance loaded by a previous Session
session = factory.openSession();
Transaction t = session.beginTransaction();
int oldVersion = foo.getVersion();
session.load( foo, foo.getKey() ); // load the current state
if ( oldVersion != foo.getVersion() ) throw new StaleObjectStateException();
foo.setProperty("bar");
t.commit();
session.close();

The version property is mapped using <version>, and Hibernate will automatically increment it during flush if the entity is dirty.
Clearly, manual version checking is only feasible in very trivial circumstances and not practical for most applications.

2) Extended session and automatic versioning : A single Session instance and its persistent instances are used for the whole conversation, known as session-per-conversation. Hibernate checks instance versions at flush time, throwing an exception if concurrent modification is detected. It’s up to the developer to catch and handle this exception.
The Session is disconnected from any underlying JDBC connection when waiting for user interaction. This approach is the most efficient in terms of database access. The application need not concern itself with version checking or with reattaching detached instances, nor does it have to reload instances in every database transaction.

// foo is an instance loaded earlier by the old session
Transaction t = session.beginTransaction(); // Obtain a new JDBC connection, start transaction
foo.setProperty("bar");
session.flush(); // Only for last transaction in conversation
t.commit(); // Also return JDBC connection
session.close(); // Only for last transaction in conversation

3)  Detached objects and automatic versioning: Each interaction with the persistent store occurs in a new Session. However, the same persistent instances are reused for each interaction with the database. The application manipulates the state of detached instances originally loaded in another Session and then reattaches them using Session.update(), Session.saveOrUpdate(), or Session.merge().
// foo is an instance loaded by a previous Session
foo.setProperty("bar");
session = factory.openSession();
Transaction t = session.beginTransaction();
session.saveOrUpdate(foo); // Use merge() if "foo" might have been loaded already
t.commit();
session.close();

Again, Hibernate will check instance versions during flush, throwing an exception if conflicting updates occurred.

4) Customizing automatic versioning
You may disable Hibernate’s automatic version increment for particular properties and collections by setting the optimistic-lock mapping attribute to false. Hibernate will then no longer increment versions if the property is dirty.
Legacy database schemas are often static and can’t be modified. Or, other applications might also access the same database and don’t know how to handle version numbers or even timestamps. In both cases, versioning can’t rely on a particular column in a table. To force a version check without a version or timestamp property mapping, with a comparison of the state of all fields in a row, turn on optimistic-lock=”all” in the <class> mapping
Sometimes concurrent modification can be permitted as long as the changes that have been made don’t overlap. If you set optimistic-lock=”dirty” when mapping the <class>, Hibernate will only compare dirty fields during flush