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

Building Application with Spring Boot

Spring Boot makes very easy to build standalone as well as production grade Spring based application. I found features like "Embedded Tomcat and Jetty. no need to deploy war. also XML based configuration eliminated" - interesting !

Spring Boot Features :
  • Create Stand Alone Spring based Application
  • No need for XML Configuration
  • Embedded Tomcat and Jetty (no need to deploy war)
  • Configure Spring Automatically whenever possible
  • Maven Configuration simplified
  • Provide production ready features like health check and externalized Configuration.

Common Aware Interfaces used in Spring

If You are developing application using Spring then sometime it's important that your beans aware about Spring IOC container resources. Here, Spring Aware comes into picture.

To use Aware Interfaces, You bean class should implement aware interfaces. and That's way they will be aware about container resources. I like to use these interfaces :)

Common Aware Interfaces used in Spring 3.2:
  1. BeanNameAware
  2. ApplicationContextAware
  3. BeanFactoryAware
  4. MessageSourceAware
  5. ApplicationEventPublisherAware
  6. ResourceLoaderAware

Spring @PostConstruct and @PreDestroy annotation Example

If You want to perform specific action or handling upon bean Initialization and Bean destruction then Implementing InitializingBean and Disposable Bean or init-method and destroy-method is for You !!

But there is another annotation approach available. You need to annotate methods with @PostConstruct and @PreDestroy annotation in you bean class and define in Spring Bean configuration file.

You can either add CommonAnnotationBeanPostProcessor (org.springframework.context.annotation.CommonAnnotationBeanPostProcessor) class in Spring bean xml or use context:annotation-config in spring bean configuration file

Init-method and Destroy-method Spring Bean example

If You want to perform specific action or handling upon bean Initialization and Bean destruction then Implementing InitializingBean and Disposable Bean is for You !!

But there is another approach also available if you don't want to implement those interfaces..You can add init-method and destroy-method into your spring bean configuration file at bean level.

Difference between context:component-scan and context:annotation-config in Spring

<context:component-scan/> scan packages and classes within given base packages then find and register beans into ApplicationContext.It does all things that <context:annotation-config/> is supposed to do.
So if you have used annotation for example, @Autowired in your code and <context:component-scan/> in xml then You do not require to use <context:annotation-config/>

What is ApplicationContext and BeanFactory in Spring?

ApplicationContext(org.springframework.context.ApplicationContext) is interface provided by Spring  and it's used for getting Configuration information about your application.Spring has many classes which implements this interface.

What are common Implementation of ApplicationContext ? - They are
  1. ClassPathXmlApplicationContext
  2. FileSystemXmlApplicationContext
  3. XmlWebApplicationContext

Spring InitializingBean and DisposableBean Example

In Spring, If You want to perform specific actions on Bean Initialization or Destruction then Spring abstract Interface InitializingBean and DisposableBean are for You !

InitializingBean is abstract interface which has abstract method called afterPropertiesSet. If You have any bean which implements this interface then after all bean properties are set, this afterPropertiesSet method will be called.

DisposableBean is abstract Interface which has abstract method called destroy. If You have any bean which implements this interface then after bean is released by Spring container, this method will be called.

Generate BeanName using Spring AnnotationBeanNameGenerator

Developing application with Spring, sometimes require to retrieve bean name which you have either specified in @Bean annotation or bean id which is internally generated by Spring.

Spring by Default generate Bean id same as Bean class name but with first letter in small caps.
Using Spring AnnotationBeanNameGenerator class, one can achieve this using generateBeanName method.

Ex. private AnnotationBeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();
String beanName = this.beanNameGenerator.generateBeanName(definition, registry); 

Here,
(1) definition is Spring BeanDefinition. BeanDefinition describes bean instance which has property values, constructor argument values any many more.

In order to retrieve BeanDefinition for bean, method resolveScopeMetadata(BeanDefinition definition) of Spring interface like ScopeMetadatResolver or AnnotationScopeMetadataResolver can be used.


Spring provide interface called AnnotatedBeanDefinition which provide awesome bean information like getMetadata() for those beans which has annotation defined.

(2) registry is of Spring BeanDefinitionRegistry.(Ex. BeanDefinitionRegistry registry)  it's basically interface for registries which holds bean Definition. It's only interface which encapsulate registries of bean Definition

After struggling hours , I finally able to make things working. Hope you find this information useful

Prefix mvc for element mvc:annotation-driven is not bound

If you are planning to use <mvc:annotation-driven>  into your Spring MVC application, chances that you may be facing issue for "Prefix mvc for element mvc:annotation-driven is notbound " erorr. Root cause is that your bean definition XML doesn't have names-spaces mentioned below.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

While developing SpringMVC application in Eclipse, All require dependencies has been added to maven dependencies in pom.xml. Yet running application encountered with Exception java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

Solution : 
Even though you have added all required dependencies into pom.xml for your J2EE WebProject you are require to reference maven dependencies to "Web Deployment Assembly"

Right Click J2EE Web Project->Deployment Assembly->Add->Select Maven Dependencies.

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

I was working on developing Spring MVC Application with Maven+Tomcat with Spring 3.2. While running application, encountered with Exception : java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

Solution :
I found that tomcat container doesn't contain jatl library and hence require to explicitly add it to maven dependencies in Pom.xml

Maven Dependencies
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

After adding maven dependencies as mentioned above, issue is resolved. Hope it might help you.

Spring org.springframework.beans.BeanInstantiationException - Solved

I was working on JAX-RS and encountered with BeanInstantiationException.

Exception :
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.anuj.services.CountryServiceImpl]: Constructor threw exception; nested exception is com.anuj.common.errors.InternalServerException: Internal Server Error Occured
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:162)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:76)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:983)
    ... 41 more
Caused by: com.anuj.common.errors.InternalServerException: Internal Server Error Occured
    at com.anuj.services.CountryServiceImpl.initialize(CountryServiceImpl.java:160)
    at com.anuj.services.CountryServiceImpl.(CountryServiceImpl.java:44)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
    ... 43 more


Sending Email using Spring MailSender and Gmail SMTP Server

Spring provides interface called "MailSender" (org.springframework.mail.MailSender) to send mail.
Developer can use MailSender method send(SimpleMailMessage simpleMessage)and pass SimpleMailMessage with From,To,Subject, and Text set.

MailSender Documentation : MailSender
SimpleMailMessage Documentation : SimpleMailMessage


Java Program to send Mail using Spring MailSender :
package com.anuj.spring.mail;

import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

/**
 *
 * @author Anuj Patel
 */
public class NotifyImpl {
    
    private MailSender mailsender;
    
    public MailSender getMailsender() {
        return mailsender;
    }
    
    public void setMailsender(MailSender mailsender) {
        this.mailsender = mailsender;
    }
    
    public void sendMail(String from, String to, String subject, String message) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(message);
        
        mailsender.send(simpleMailMessage);
    }
} 

Spring - java.lang.ClassNotFoundException: org.aopalliance.aop.Advice

Even after adding all Spring 3.1 jar i was getting excpetion as below :

Exception in thread "main" org.springframework.beans.factory.CannotLoadBeanClassException:
Caused by: java.lang.ClassNotFoundException: org.aopalliance.aop.Advice
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 49 more
   
Solution :

As part of https://jira.springsource.org/browse/SPR-2011, Removed AOP Alliance interfaces from spring-aop.jar and
the aopalliance.jar needs to be added explicitly. Instead of using jar from any other sources, it's better to use jar from official maven repository.

How to load multiple Spring bean configuration file

When you are working on large project where stracturized  folder structure is being used for Spring Beans configuration files ex. Spring-Core.xml in Core Folder, Spring-Common.xml in Common folder etc

You may load multiple Spring bean configuration files in code :
ApplicationContext context = 
     new ClassPathXmlApplicationContext(new String[] {"Spring-Core.xml",
              "Spring-Common.xml"});

This way is not properly organized.It will be better if we can import multiple xml into one xml and then define single main XML into ClassPathXmlApplicationContext
Ex. 
<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">    
       <import resource="common/Spring-Core.xml"/>  
      <import resource="connection/Spring-Common.xml"/> 
</beans>

Deep Dive into Spring Setter Injection

Spring setter injection provide you to set value of different types of Data which you use while developing application. If you are not aware of Constructor or Setter Injection concept, please refer Spring Setter Injection and Constructor Injection before going through tutorial.

I will show you how to use it Spring setter Injection for different types of data.somehow due to formatting String is displayed as string.please use String in your example.

1. Create PropertyTest.java
package com.anuj.spring.core.injection;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 *
 * @author Anuj J Patel
 */
public class PropertyTest {
    
    private int intData;
    private double doubleData;
    private float floatData;
    private String stringData;
    private int[] intArr;
    private String[] stringArr;
    private List listdata;
    private Map map;
    private Properties properties;
    private Set setData;

    public PropertyTest() {
        System.out.println("Constructor Called");
    }
    
    @Override
    public String toString() {
        return "PropertyTest{" + "intData=" + intData + ", doubleData=" + doubleData + ", floatData=" + floatData + ", stringData=" + stringData + ", intArr=" + intArr + ", stringArr=" + stringArr + ", listdata=" + listdata + ", map=" + map + ", properties=" + properties + ", setData=" + setData + '}';
    }
    
    public double getDoubleData() {
        return doubleData;
    }

    public void setDoubleData(double doubleData) {
        this.doubleData = doubleData;
    }

    public float getFloatData() {
        return floatData;
    }

    public void setFloatData(float floatData) {
        this.floatData = floatData;
    }

    public int[] getIntArr() {
        return intArr;
    }

    public void setIntArr(int[] intArr) {
        this.intArr = intArr;
    }

    public int getIntData() {
        return intData;
    }

    public void setIntData(int intData) {
        this.intData = intData;
    }

    public List getListdata() {
        return listdata;
    }

    public void setListdata(List listdata) {
        this.listdata = listdata;
    }

    public Map getMap() {
        return map;
    }

    public void setMap(Map map) {
        this.map = map;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public Set getSetData() {
        return setData;
    }

    public void setSetData(Set setData) {
        this.setData = setData;
    }

    public String[] getStringArr() {
        return stringArr;
    }

    public void setStringArr(String[] stringArr) {
        this.stringArr = stringArr;
    }

    public String getStringData() {
        return stringData;
    }

    public void setStringData(String stringData) {
        this.stringData = stringData;
    }
}

Spring JdbcTemplate and Spring SimpleJdbcTemplate difference with Example

To use the SimpleJdbcTemplate you need to use JDK 1.5 or higher. SimpleJdbcTemplate takes advantage of the Java 5 language features like varargs, autoboxing, generics and covariant returns.

Following example shows you how to use SimpleJdbcTemplate and advantage of it over JdbcTemplate
package com.anuj.spring.db;

import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

/**
 *
 * @author Anuj J Patel
 */
public class ForumDAOSimpleJDBCImpl implements ForumDAO{

    /**
     * Simple JDBCTemplate
     * 1.When using SimpleJDBCTemplate there is no need to typecast from int to Integer
     * and you can pass variable length arguments instead of Object array
     * 2.There is no need to typecast return object, parameterizedRowMapper object's type parameter 
     * will be taken by default
     */
    private SimpleJdbcTemplate simpleJDBCTemplate;
    
    public void setDataSource(DataSource dataSource){
        this.simpleJDBCTemplate = new SimpleJdbcTemplate(dataSource);
    }
    
    @Override
    public void insert(Forum forum) {
        String query = "insert into tbforum(forumId,forumName,forumDesc) values(?,?,?)";
        simpleJDBCTemplate.update(query, forum.getForumId(),forum.getForumName(),forum.getForumDesc());
        System.out.println("Record Inserted successfully");
    }

    @Override
    public Forum selectForum(int forumId) {
        String query="select * from tbforum where forumId=?";
        
        return simpleJDBCTemplate.queryForObject(query, 
                new ParameterizedRowMapper(){
                        @Override
                        public Forum mapRow(ResultSet rs, int rowNum) throws SQLException {
                            return new Forum(rs.getInt("forumId"),rs.getString("forumName"), rs.getString("forumDesc"));
                        };               
                },forumId);        
    }
    
}

Spring Setter Injection and Constructor Injection

In this post i am going to demonstrate you how to set bean property using spring setter injection and constructor. First i will demonstrate Happy scenario and later will be complex. This will force you to think deeply about bean.xml

Consider i have class User containing 3 property name,age and country. Using spring i want to display value of user with all it's property.

User.java
package com.anuj.spring.injection;
/**
 *
 * @author Anuj J Patel
 *
 */
public class User {

    private String name;
    private int age;
    private String country;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String toString()
    {
        String output = "Name : " + name + " Age: " + age + " Country:" + country;
        return output;
    }
}

Spring IOC and Dependancy Injection

In Spring, Inversion of Control(IOC) is implemented using Dependancy Injection(DI) Design Pattern. Let's understand DI with java example and then I will see how DI can solve tightly coupled problem and Spring container will inject dependency.

What is Inversion of Control?
IOC allows you to decouple your program into separate components that don't know each other. supposed if I have two classes which implements common interface then In order to use, In my Java class i need to create instance of those classes. which looks like tightly coupled.

If we can define which class to use at runtime using Injecting dependency at runtime then it will be good , right? This is where IOC comes to Picture.

Concept IoC that the Spring Framework uses is "Injection of required resources or dependency at Run-time into the dependent resource," which is also known as Dependency Injection.

There are three forms or styles of Dependency Injection.
1.Constructor Injection
2.Setter Injection
3.Interface Injection

1. Constructor Injection: Here, IoC container uses the constructor to inject the dependency. Since All dependencies are declared in one constructor, it's added advantage.
- here, handling over dependencies takes during instantiation of the dependent object.

2. Setter Injection: Here, DI uses Setters to inject the required resources or dependencies.Meaning class will have setters, the IoC container will use the setters to provide the resource at run-time.
-  here, handling over dependencies takes after the dependent object is instantiated

What is Spring and why came into Picture ?

In order to start with Spring, it's very important to clear concepts about what is Spring and why it came into picture. Once you have idea about Spring picture, you will be sure able to easily understand 7 Spring modules described here as well. So Let's Jump into Spring :)

Java Enterprise Edition (JEE) component that was used to implement business logic was Enterprise Java Beans (EJB). However, EJBs are heavy weight components that require application servers to run. 

This was the scenario before the Spring Framework came into the picture. The Spring Framework provides a lightweight container to run the objects implementing business logic. In other words, Spring Framework-based business objects do not require an application server to run.

Spring Framework: What is it? Spring Framework is “An open-source layered Java/J2EE application framework having a light-weight container implementing Inversion-of-Control and Aspect Oriented Programming.” The key points here are “layered application framework” and “Inversion of Control and Aspect Oriented Programming.” and they are divided into two broad categories:
  1. Patterns
  2. Components of the Framework

Spring has two patterns at its core. They are:
    • Inversion-of-Control(IOC)
    • Aspect Oriented Programming(AOP)

Inversion-of-Control - refer to Spring DI and IOC concept and Example

Aspect Oriented Programming(AOP) is “An approach to programming that attempts the separation of concerns, specifically cross-cutting concerns, as an advance in modularization.” Here, the key point is separation of concerns. 

Separation of concerns means that the applications are divided into modules that do not overlap in terms of functionality.Logging is an example of such a concern.by using AOP a developer can encapsulate cross cutting concerns.