To know more about java tutorials.... Click here
More Javascript tutorials you can found here

Methods of Bean Configurations for Spring Container

June 20, 2015 Leave a comment

There are three ways to provide the configuration metadata to Spring container. Below are the more details about them.

1. Xml based configuration file

<?xml version=”1.0″ encoding=”UTF-8″?>

<beans xmlns=”http://www.springframework.org/schema/beans&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”&gt;

<!– A simple bean definition –>
<bean id=”…” class=”…”>
<!– collaborators and configuration for this bean go here –>
</bean>

<!– A bean definition with lazy init set on –>
<bean id=”…” class=”…” lazy-init=”true”>
<!– collaborators and configuration for this bean go here –>
</bean>

<!– A bean definition with initialization method –>
<bean id=”…” class=”…” init-method=”…”>
<!– collaborators and configuration for this bean go here –>
</bean>

<!– A bean definition with destruction method –>
<bean id=”…” class=”…” destroy-method=”…”>
<!– collaborators and configuration for this bean go here –>
</bean>

<!– more bean definitions go here –>

</beans>

2. Annotation based configuration

<?xml version=”1.0″ encoding=”UTF-8″?>

<beans xmlns=”http://www.springframework.org/schema/beans&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xmlns:context=”http://www.springframework.org/schema/context&#8221;
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd”&gt;

<context:annotation-config/>
<!– bean definitions go here –>

<bean id=”empAddress” class=”in.malliktalksjava.spring.samples.EmployeeAddress” />

</beans>

Once <context:annotation-config/> is configured, you can start annotating your code to indicate that Spring should automatically wire values into properties, methods, and constructors. Once you add the annotation config, you can use @Autowired annotation as below on setter methods to get rid of the <property> element in XML configuration file. When Spring finds an @Autowired annotation used with setter methods, it tries to perform byType autowiring on the method.

Employee.java:

package in.malliktalksjava.spring.samples;

public class Employee{

@Autowired

public EmployeeAddress empAddress;

public void test(){

System.out.println(empAddress.getStreet());

System.out.println(empAddress.getPostalCode());

}

}

EmployeeAddress.java:

package in.malliktalksjava.spring.samples;

public class EmployeeAddress{

private String street;

private String postalCode;

public void setStreet(String street){

this.street = street;

}

public String getStreet(){

return street;

}

public void setPostalCode(String postalCode)

this.postalCode = postalCode;

}

public String getPostalCode(){

return postalCode;

}

}

 

3. Java based configuration

Java based configuration option enables you to write most of your Spring configuration without XML but with the help of few Java-based annotations. Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context.

HelloWorldConfig.java

package in.malliktalksjava.spring.samples;
import org.springframework.context.annotation.*;

@Configuration
public class HelloWorldConfig {

@Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}

HelloWorld.java

package in.malliktalksjava.spring.samples;

public class HelloWorld {
private String message;

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

public void getMessage(){
System.out.println(” Message is : ” + message);
}
}

MainApp.java:

package in.malliktalksjava.spring.samples;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;

public class MainApp {
public static void main(String[] args) {
ApplicationContext ctx =
new AnnotationConfigApplicationContext(HelloWorldConfig.class);

HelloWorld helloWorld = ctx.getBean(HelloWorld.class);

helloWorld.setMessage(“Hello World!”);
helloWorld.getMessage();
}
}

Complete application has been created without writing any configuration file.

Spring Bean Scopes – Examples

June 20, 2015 Leave a comment

There are 5 spring bean scopes as below:

1. Singleton: 

If scope is set to singleton, the Spring IoC container creates exactly one instance of the object defined by that bean definition. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object.

If we not set any scope to bean then spring container will set to the default scope and default scope of the bean is always singleton. use ‘singleton’ to set the bean scope to Singleton.

2. Prototype

If scope is set to prototype, the Spring IoC container creates new bean instance of the object every time a request for that specific bean is made.

Use ‘prototype’ word during spring configuration to set the bean scope to Proto Type.

As a rule, use the prototype scope for all state-full beans and the singleton scope for stateless beans.

3. Request:

This scopes a bean definition to an HTTP Request and its only valid in the context of a web-aware Spring ApplicationContext.

Use the ‘request’ keyword to set the bean scope to HttpRequest during spring bean configuration.

4. Session:

This scopes a bean definition to an HTTP Session and its only valid in the context of a web-aware Spring ApplicationContext.

Use the ‘session’ keyword to set the bean scope to Http Session during spring bean configuration.

5. Global Session

This scopes a bean definition to a Global HTTP Session and its only valid in the context of a web-aware Spring ApplicationContext.

Use the ‘global-session’ keyword to set the bean scope to Global Http Session during spring bean configuration.

Configuration of these scopes can be done as below:

Define the above mentioned scopes in beans.xml file along with bean declaration.

<!– A bean definition with singleton scope –>
<bean id=”…” class=”…” scope=”singleton”>
<!– collaborators and configuration for this bean go here –>
</bean>

Can also be mention the bean scope using annotation:

@Configuration
public class BeanJavaConfiguration {
@Bean
@Scope(“prototype”)
public Appleapp() {
return new Apple();
}
}

 

How to Inject Null or Blank values to a Spring Bean

June 20, 2015 Leave a comment

To inject an NULL value which is equivalent to bean.setMessage(null):

<bean id=”beanId” class=”bean”>
<property name=”message”><null/></property>
</bean>

To inject an empty Stringe which is equivalent to bean.setMessage(“”)

<bean id=”beanId” class=”bean”>
<property name=”message” value=””></property>
</bean>

 

Different Types of Spring Containers

June 20, 2015 Leave a comment

There are two distinct types of spring containers as mentioned below:

1. BeanFactory Container:

This is the simplest container providing basic support for Dependency Injection and defined by the org.springframework.beans.factory.BeanFactory interface. The BeanFactory and related interfaces, such as BeanFactoryAware, InitializingBean, DisposableBean, are still present in Spring for the purposes of backward compatibility with the large number of third-party frameworks that integrate with Spring.

2. ApplicationContext Container:

This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners. This container is defined by the org.springframework.context.ApplicationContext interface.

The ApplicationContext container includes all functionality of the BeanFactory container, so it is generally recommended over the BeanFactory. BeanFactory can still be used for light weight applications like mobile devices or applet based applications where data volume and speed is significant.

Is it mandatory to have the “id” property in Bean/ApplicationContext Xml

May 30, 2015 Leave a comment

Typical Bean xml file looks like below:

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=”http://www.springframework.org/schema/beans&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd&#8221; >

<bean class=”in.malliktalksjava.service.MyServiceImpl”>

<property name=”repository” ref=”someDAO”/>
</bean>

<bean id=”someDAO” class=”in.malliktalksjava.dao.SomeDao”/>

</beans>

MyServiceImpl Bean is anonymous because no id is supplied explicitly. Thus Spring container generates a unique id for that bean. It uses the fully qualified class name and appends a number to them. However, if you want to refer to that bean by name, through the use of the ref element you must provide a name (see Naming Beans section of the Spring reference manual). To be correct, the 2nd bean has to declare a someDAO id attribute in order to be reference by the repository property of the first bean

Spring Core – Hello World Example

May 28, 2015 Leave a comment

Pre Requisite :

Download and install the Spring STS into your machine. This will provide all the default spring configurations whenever you create the project

Application Creation Steps:

Step 1: Spring Maven project in your STS. This gives the project folder structure and one pom.xml file in root folder. Below is the Sample pom Xml.

<project xmlns=”http://maven.apache.org/POM/4.0.0&#8243; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”&gt;
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.samples</groupId>
<artifactId>Spring-Project</artifactId>
<version>0.0.1-SNAPSHOT</version>

<properties>

<!– Generic properties –>
<java.version>1.6</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

<!– Spring –>
<spring-framework.version>3.2.3.RELEASE</spring-framework.version>

<!– Hibernate / JPA –>
<hibernate.version>4.2.1.Final</hibernate.version>

<!– Logging –>
<logback.version>1.0.13</logback.version>
<slf4j.version>1.7.5</slf4j.version>

<!– Test –>
<junit.version>4.11</junit.version>

</properties>

<dependencies>
<!– Spring and Transactions –>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>

<!– Logging with SLF4J & LogBack –>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>

<!– Hibernate –>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!– Test Artifacts –>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>

</dependencies>
</project>

Step 2: Create the bean class HelloWorldBean.java as below

package in.malliktalksjava.spring.examples;

public class HelloWorldBean {

private String message;

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

public void printMessage(){
System.out.println(“You are in Print Message : “+message);
}
}

Step 3: Create Beans Xml file and configure the HellowWorldBean into that file to make use of dependency injection.

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=”http://www.springframework.org/schema/beans&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd”&gt;
<bean id=”helloWorldBean” class=”in.malliktalksjava.spring.examples.HelloWorldBean”>
<property name=”message” value=”Hello World”></property>
</bean>

</beans>

Step 4: Create the Main Application class SpringCoreBeansXmlExample.java and load the beans xml

package in.malliktalksjava.spring.examples;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
* @author mallikarjungunda
*
*/
public class SpringCoreBeansXmlExample {

/**
* @param args
*/
public static void main(String[] args) {

//Load the beans.xml into Application Context
ApplicationContext context = new ClassPathXmlApplicationContext(“beans.xml”);

//Inject the object whenever required
HelloWorldBean helloWorldBean = (HelloWorldBean)context.getBean(“helloWorldBean”);

helloWorldBean.printMessage();
}
}

Below is the out put that prints whenever you run the class.

You are in Print Message : Hello World

 

Thank you for going through the this example. Refer to Menu bar for other tutorials.

Difference between ClassNotFoundException and NoClassDefFoundError

May 27, 2015 Leave a comment

1. java.lang.ClassNotFoundException :  This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.

2. java.lang.NoClassDefFoundError :  This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason – now we’re trying to use the class again (and thus need to load it, since it failed last time), but we’re not even going to try to load it, because we failed loading it earlier (and reasonably suspect that we would fail again). The earlier failure could be a ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a classpath problem.

Difference between HttpSession’s getSession(), getSession(true) and getSession(false) methods

December 30, 2014 Leave a comment

getSession() : Returns the current session associated with this request, or if the request does not have a session, creates one.

getSession(true) : Returns the current HttpSession associated with this request, if there is no current session, returns a new session

getSession(false) : Returns the current HttpSession associated with this request, if there is no current session, returns null.

org.springframework.beans.NotReadablePropertyException: Invalid property

December 1, 2014 Leave a comment

Exception:

ERROR: org.springframework.web.servlet.tags.form.RadioButtonTag – Invalid property ‘newUser’ of bean class [com.malliktalksjava.bean.UserBean]: Bean property ‘newUser’ is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
org.springframework.beans.NotReadablePropertyException: Invalid property ‘newUser’ of bean class [com.malliktalksjava.bean.UserBean]: Bean property ‘newUser’ is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
at org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:725)
at org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:716)
at org.springframework.validation.AbstractPropertyBindingResult.getActualFieldValue(AbstractPropertyBindingResult.java:99)
at org.springframework.validation.AbstractBindingResult.getFieldValue(AbstractBindingResult.java:229)
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:120)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:154)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.autogenerateId(AbstractDataBoundFormElementTag.java:141)
at org.springframework.web.servlet.tags.form.AbstractCheckedElementTag.autogenerateId(AbstractCheckedElementTag.java:81)

Solution:

Ensure all the properties configured in the form are available in the FormBean object. In the above case the radio button property have not been configured in my UserBean class.

Features of Spring Web MVC

September 22, 2014 Leave a comment

Spring’s web module includes many unique web support features:

  • Clear separation of roles. Each role — controller, validator, command object, form object, model object, DispatcherServlet, handler mapping, view resolver, and so on — can be fulfilled by a specialized object.
  • Powerful and straightforward configuration of both framework and application classes as JavaBeans. This configuration capability includes easy referencing across contexts, such as from web controllers to business objects and validators.
  • Adaptability, non-intrusiveness, and flexibility. Define any controller method signature you need, possibly using one of the parameter annotations (such as @RequestParam, @RequestHeader, @PathVariable, and more) for a given scenario.
  • Reusable business code, no need for duplication. Use existing business objects as command or form objects instead of mirroring them to extend a particular framework base class.
  • Customizable binding and validation. Type mismatches as application-level validation errors that keep the offending value, localized date and number binding, and so on instead of String-only form objects with manual parsing and conversion to business objects.
  • Customizable handler mapping and view resolution. Handler mapping and view resolution strategies range from simple URL-based configuration, to sophisticated, purpose-built resolution strategies. Spring is more flexible than web MVC frameworks that mandate a particular technique.
  • Flexible model transfer. Model transfer with a name/value Map supports easy integration with any view technology. Customizable locale, time zone and theme resolution, support for JSPs with or without Spring tag library, support for JSTL, support for Velocity without the need for extra bridges, and so on.
  • A simple yet powerful JSP tag library known as the Spring tag library that provides support for features such as data binding and themes. The custom tags allow for maximum flexibility in terms of markup code. For information on the tag library descriptor, see the appendix entitled Chapter 36, spring.tld
  • A JSP form tag library, introduced in Spring 2.0, that makes writing forms in JSP pages much easier.
  • Beans whose lifecycle is scoped to the current HTTP request or HTTP Session. This is not a specific feature of Spring MVC itself, but rather of the WebApplicationContext container(s) that Spring MVC uses. These bean scopes are described in the section called “Request, session, and global session scopes”

Source:

http://docs.spring.io/spring/docs/current/spring-framework-reference/pdf/spring-framework-reference.pdf

Follow

Get every new post delivered to your Inbox.

Join 558 other followers