Tuesday, 23 July 2019

Lamda Expression

What is Lamda Expression.

It is essentially, an  anonymous (that is unnamed) method. However this method is not executed on its own. Instead it is used to implement a method defined by a functional interface. Thus a lamda expression results in a form of anonymous class . These are also referred to as closures. 

If we are learning about the Lamda expressions, it is very much required to learn about the Functional Interfaces.

A Functional Interface is an interface that contains one and only one abstract method. It can have any number of default ,static methods.

Default Method.

It is possible to specify default behaviour for a method declared in an interface this is called a default method.

Before Java 8 when a new method is added to the interface then it has to be implemented in the Implementing classes but with the help of default method we can have methods with implementation without affecting the classes that implement the Interface.

Eg:Sample Program Here the Method greetAll is the default method and not required to be implemented in all
the implementing classes.

package com.searchendeca.java8Tutorials;

@FunctionalInterface
public interface GettingStarted {
abstract String greetMessage();
default void greetAll() {
System.out.println("Hello All");
}
}


class gettingMain{


public static void main(String args[]) {

GettingStarted getValue;
getValue = ()->"Welcome Syed Ghouse";
System.out.println(getValue.greetMessage());
}



Method Reference

A method refrence provides a way to refer to a method without executing it.

There are three ways of method refrence avalible .

1. Method Reference to static methods.

It can be called using. ClassName::MethodName

2.Reference to an instance method.

ContainingObject:: Instance Methods.

3. Refrence to Constructor.

className::new

Here is the sample program.

package com.searchendeca.java8Tutorials;

@FunctionalInterface
public interface MethodRefrence {
abstract void greetMessage();
default void greetAll() {
System.out.println("Hello All");
}
}

package com.searchendeca.java8Tutorials;

public class SampleMethodRefrence implements MethodRefrence {

@Override
public void greetMessage() {
System.out.println("Welcome Syed Ghouse Habib");
}

public static String greetAllMessage() {
// TODO Auto-generated method stub
return "Welcome Syed Ghouse Habib";
}

}

package com.searchendeca.java8Tutorials;

public class InvokerMethodRefrence {
public static void main(String args[]) {
System.out.println("**********************");
SampleMethodRefrence samRef = new SampleMethodRefrence();
MethodRefrence sam=SampleMethodRefrence::greetAllMessage;// Method refrence to static methods
MethodRefrence sam1=samRef::greetMessage;//Method Refrence to Non Static methods(instance method names)
sam1.greetMessage();
}

}

package com.searchendeca.java8Tutorials;

interface MessagePrint{  
conctructMess getMessage(String msg);  
}  
class conctructMess{  
conctructMess(String msg){  
System.out.print(msg);  
}  
}  
public class ConstructorReference {  
public static void main(String[] args) {  
MessagePrint hello = conctructMess::new;   //Refrence to Constructor.
hello.getMessage("Hello");  
}  
}

Configuring Spring MVC Through Java

In our Earlier posts we have seen how to set up the MVC application through the XML based, now in this blog we are going to see how to configure only through the java based.

For this on top of the existing setup we have from last tutorial.

Perform the Following changes to the application .

1.Here is my web.xml

In My Web.xml I need to define the contextconfig location to the AppConfig.java

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext
        instead of the default XmlWebApplicationContext -->
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </context-param>
    <!-- Configuration locations must consist of one or more comma- or space-delimited
        fully-qualified @Configuration classes. Fully-qualified packages may also be
        specified for component-scanning -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.searchendeca.configuration.AppConfig</param-value>
    </context-param>
    <!-- Bootstrap the root application context as usual using ContextLoaderListener -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- Declare a Spring MVC DispatcherServlet as usual -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- Configure DispatcherServlet to use AnnotationConfigWebApplicationContext
            instead of the default XmlWebApplicationContext -->
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>
                org.springframework.web.context.support.AnnotationConfigWebApplicationContext
            </param-value>
        </init-param>
        <!-- Again, config locations must consist of one or more comma- or space-delimited
            and fully-qualified @Configuration classes -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>com.searchendeca.configuration.AppConfig</param-value>
        </init-param>
    </servlet>
    <!-- map all requests for /app/* to the dispatcher servlet -->
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>


2.Here is my pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>
<groupId>com.searchendeca.application</groupId>
<artifactId>springmvc</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Simple webapp</name>
<description>The bare minimum for a functional webapp.</description>
<url>https://github.com/mkspcd/MavenArchetypes</url>

<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>


<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>

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

<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>


</dependencies>

<properties>
<servlet.api.version>3.1.0</servlet.api.version>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

<build>
<finalName>simple-webapp</finalName>
</build>
</project>


3.AppConfig.java

package com.searchendeca.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;


@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com.searchendeca.springmvc")
public class AppConfig extends WebMvcConfigurerAdapter{


/*@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }*/
@Bean
public UrlBasedViewResolver getITRVR() {
UrlBasedViewResolver irvr = new UrlBasedViewResolver();
irvr.setViewClass(JstlView.class);
irvr.setPrefix("/WEB-INF/jsp/");
irvr.setSuffix(".jsp");
return irvr;
}

}


4.CustomDispatcherServlet.java

package com.searchendeca.configuration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

@Configuration
public class CustomDispatcherServlet implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext dispatcherServletContext = new AnnotationConfigWebApplicationContext();
        dispatcherServletContext.register(AppConfig.class);
        DispatcherServlet dispatcherServlet = new DispatcherServlet(dispatcherServletContext);
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", dispatcherServlet);
        dispatcher.setLoadOnStartup(1);
        // Add servlet mapping url. All url end with .html will be processed by this servlet.
        dispatcher.addMapping("/");
    }

}

5.Helloworld.java

package com.searchendeca.springmvc;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HelloWorld {
@RequestMapping(value="/welcome")
public String greetmessage(Model model) {
model.addAttribute("message", "Hello Syed Welcome!");
System.out.println("Syed");
return "index";
}

}


6.Index.jsp

<%@ page language="java" pageEncoding="UTF-8" %>

${message}


Output:Hello Syed Welcome!


Happy Learning !!!!

Monday, 22 July 2019

Spring MVC Framework

Web MVC framework

The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet
that dispatches requests to handlers, with configurable handler mappings, view resolution, locale, time zone and theme resolution as well as support for uploading files.

"Open for extension…" A key design principle in Spring Web MVC and in Spring in general is the
"Open for extension, closed for modification" principle.

Features of Spring Web MVC

Clear separation of roles.
Powerful and straightforward configuration of both framework and application classes as JavaBeans
Adaptability, non-intrusiveness, and flexibility
Reusable business code, no need for duplication
Customizable binding and validation.
Customizable handler mapping and view resolution
Flexible model transfer
Customizable locale, time zone and theme resolution.
A simple yet powerful JSP tag library known as the Spring tag library that provides support for features
such as data binding and themes.
If you do not want to use Spring’s Web MVC, but intend to leverage other solutions that Spring
offers, you can integrate the web MVC framework of your choice with Spring easily.

The DispatcherServlet

Spring’s web MVC framework is, like many other web MVC frameworks, request-driven, designed
around a central Servlet that dispatches requests to controllers and offers other functionality that
facilitates the development of web applications.

Now we can look into how to Create a sample mvc web application using STS.

Open the STS and select the 

File-> New Maven Project.

Leave the selected options available.



In the architypes selection select the web



Give the maven artifact and package details.



click finish to create the project.

The Project structure will be like below.



Now its our time to add the dependencies .Add the Following dependencies. Navigate to pom and paste the below Maven dependencies.

<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
</dependencies>

We have added the dependencies, now We need to update the web.xml.
As we already know that the "DispatcherServlet" is required for the dispatching the requests the corresponding controllers. Define in the following way .
<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

<display-name>Simple web application</display-name>

<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

</web-app>

Now we have defined the web.xml contents . Next is to Create the servlet-config.xml. By Default sprinng looks fot the <ServletName>-servlet.xml. Hence my servlet file name will be like spring-servlet.xml.

Here is my config file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">

// we are defining that it works based on the mvc annotation-driven hence we are mentioning like this.
<mvc:annotation-driven />
//Scans for the controller classes.
<context:component-scan
base-package="com.searchendeca.springmvc" />
<mvc:default-servlet-handler />

 //View resolver is used to resolve the view. This is very much required what the outout must be.
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>

</beans>

Create a Controller

Always create the java classes in src/main/java.

package com.searchendeca.springmvc;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloWorld {
@RequestMapping("/")
public String greetmessage(Model model) {
model.addAttribute("message", "Hello Syed Welcome!");
return "index";
}

}

From the above controller we are defining the mapping be '/' and dispatcher servlet fwds the request for / and in the model attribute we are setting and sending it .

In the view resolver we have defined as the /WEB-INF/jsp/ for the location of jsp. Create a folder there and save the jsp as index.jsp.

<%@ page language="java" pageEncoding="UTF-8" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
    ${message}
</body>
</html>

This will print the jsp message. If you access with any other context you will get 404. Happy Learning!!!

Saturday, 20 July 2019

Annotations Based Configuration in Spring

JSR-250 Annotations in the Spring

Spring also provides support for JSR-250 annotations which include @PostConstruct, @PreDestroy and @Resource annotations.

@PostContruct – This annotation is applied to a method to indicate that it should be invoked after all dependency injection is complete.
@PreDestroy – This is applied to a method to indicate that it should be invoked before the bean is removed from the Spring context, i.e. just before it’s destroyed.
@Resource – This duplicates the functionality of @Autowired combined with @Qualifier as you get the additional benefit of being able to name which bean you’re injecting, without the need for two annotations.

@Required

The @Required annotation applies to bean property setter methods, as in the following example:

package com.searchendeca.application;

import org.springframework.beans.factory.annotation.Required;

public class HelloWorld {

private GreetingName greet;

public GreetingName getGreet() {
return greet;
}
@Required
public void setGreet(GreetingName greet) {
this.greet = greet;
}

private String mMessage;

public String getMessage() {
return mMessage;
}

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

}

<bean id="helloWorldService"
class="com.searchendeca.application.HelloWorld" scope="singleton" >
<property name="message" value="Welcome to Search Endeca" />
<!-- <property name="greet" ref="greet" /> -->
</bean>
If I dont define the property then we will be facing the below exception.

Caused by: org.springframework.beans.factory.BeanInitializationException: Property 'greet' is required for bean 'helloWorldService'

Hence it @Required got worked.

@Autowired

<bean id="helloWorldService"
class="com.searchendeca.application.HelloWorld" scope="singleton">
<!-- <property name="message" value="Welcome to Search Endeca" /> -->
<!-- <property name="greet" ref="greet" /> -->
</bean>
private GreetingName greets;

public GreetingName getGreets() {
return greets;
}
@Autowired
public void setGreets(GreetingName greets) {
this.greets = greets;
}
By the above autowired happens through the byName.
@Autowired, @Inject, @Resource, and @Value annotations are handled by a Spring
BeanPostProcessor implementations which in turn means that you cannot apply these
annotations within your own BeanPostProcessor or BeanFactoryPostProcessor types (if
any). These types must be wired up explicitly via XML or using a Spring @Bean method.


@Qualifier

Because autowiring by type may lead to multiple candidates, it is often necessary to have more control
over the selection process. One way to accomplish this is with Spring’s @Qualifier annotation. You
can associate qualifier values with specific arguments, narrowing the set of type matches so that a
specific bean is chosen for each argument.

<bean id="helloWorldService"
class="com.searchendeca.application.HelloWorld" scope="singleton">
  <property name="message" value="Welcome to Search Endeca first" /> 
<!-- <property name="greet" ref="greet" /> -->
</bean>
  <bean id="greets1" class="com.searchendeca.application.GreetingName">
  <qualifier value="first"/>
<property name="name" value="Syed" />
</bean> 
<bean id="greets2" class="com.searchendeca.application.GreetingName">
<qualifier value="second"/>
<property name="name" value="Ghouse" />
</bean>
package com.searchendeca.application;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Required;

public class HelloWorld {

private GreetingName greets;

public GreetingName getGreets() {
return greets;
}
@Autowired
@Qualifier("first")
public void setGreets(GreetingName greets) {
this.greets = greets;
}

private String mMessage;

public String getMessage() {
return mMessage;
}

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

}

Output: Hello::Syed

when @Qualifier("second")

Output: Hello::Ghouse


@Resource 

It takes a name attribute, and by default Spring interprets that value as the bean name to be
injected. In other words, it follows by-name semantics, as demonstrated in this example:

<bean id="helloWorldService"
class="com.searchendeca.application.HelloWorld" scope="singleton">
  <property name="message" value="Welcome to Search Endeca first" /> 
<!-- <property name="greet" ref="greet" /> -->
</bean>
  <bean id="greets" class="com.searchendeca.application.GreetingName">
  <qualifier value="first"/>
<property name="name" value="Syed" />
</bean>
private GreetingName greets;

public GreetingName getGreets() {
return greets;
}
@Resource
public void setGreets(GreetingName greets) {
this.greets = greets;
}
@PostConstruct and @PreDestroy
@PostConstruct also be used as the init-method if you dont want to use JSR-250.
@predestroy also be used as the destroy menthod f you dont want to use JSR-250.
public class Helloworld {
@PostConstruct
public void populateHelloworld2() {
// populates the movie cache upon initialization...
}
@PreDestroy
public void clearHelloworld2() {
// clears the movie cache upon destruction...
}
}

Class path scanning.

We have seen examples from the previous samples where the XML based and annotation based, or mix and match. Now starting from this we are going to see only the annotation based without the xml based initialization also.

1.Partial XML based.

Define the following in the applicationContext.xml

<context:component-scan base-package="com.searchendeca.application"/>

In the Bean class define it as 

@Component(value="HelloWorld")
public class HelloWorld {
private String mMessage;

public String getMessage() {
return mMessage;
}

public void setMessage(String pMessage) {
this.mMessage = pMessage;
}
}
In the main class do the following.
ApplicationContext context = new FileSystemXmlApplicationContext("/src/main/resources/applicationContext.xml");
HelloWorld service = (HelloWorld) context.getBean("HelloWorld");
service.setMessage("Syed Ghouse Habib");
System.out.println(service.getMessage());
once the class is executed then the spring initialize the beans and look for it from the component value and map it.


Starting with Spring 3.0, many features provided by the Spring JavaConfig project are part of
the core Spring Framework. This allows you to define beans using Java rather than using the
traditional XML files. Take a look at the @Configuration, @Bean, @Import, and @DependsOn
annotations for examples of how to use these new features.

2.Without XML Configuration.

Define a simple bean class.

package com.searchendeca.application;

public class HelloWorld {

private String mMessage;

public String getMessage() {
return mMessage;
}

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


}


In the configuration class or the main define the below.

package com.searchendeca.application;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration //we are defining as the configuration class
public class Hello {
@Bean // through the anotaion we are defining  the Bean Configuration classes can contain bean definition methods annotated with @Bean:

public HelloWorld getHelloWorld() {
return new HelloWorld();
}

@SuppressWarnings("resource")
public static void main(String[] args) {
// We have seen two types of the Application context earlier, since we are using the No XMl based
//We are using the AnnotationConfigApplicationContext as the context.
AnnotationConfigApplicationContext contxt = new AnnotationConfigApplicationContext();
//Scaning for the Basepackages where our bean defined.
contxt.scan("com.searchendeca.application");
contxt.refresh();
//getting the insstance of the bean class.
HelloWorld service = contxt.getBean(HelloWorld.class);
service.setMessage("Syed Ghouse Habib");
//here we can mention the name for the bean and get it 
//@Bean(name= {"getHelloWorld1","Helloworld"}) Bean aliasing
//As discussed in the section called “Naming beans”, it is sometimes desirable to give a single bean
//multiple names, otherwise known asbean aliasing. The name attribute of the @Bean annotation //accepts a String array for this purpose.
//HelloWorld service = contxt.getBean("getHelloWorld1");
System.out.println(service.getMessage());
}
}

Using @ComponentScan

In the Bean class just define the @service or @component.

In the Configuration class do the following.

package com.searchendeca.application;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;


@Configuration
@ComponentScan(basePackages = {"com.searchendeca.application"}) // This scans for all the class defined in the package.
public class Hello {
@Autowired
public static HelloWorld getHelloWorld() {
return new HelloWorld("Syed");
}



@SuppressWarnings("resource")
public static void main(String[] args) {
AnnotationConfigApplicationContext contxt = new AnnotationConfigApplicationContext();
try {
contxt.register(HelloWorld.class);
contxt.refresh();
HelloWorld service = contxt.getBean(HelloWorld.class);
System.out.println(getHelloWorld().getMessage());

}
finally {
contxt.close();
        }
}
}

Using JSR 330 Standard Annotations

If you are using Maven, the javax.inject artifact is available in the standard Maven
repository.

<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>


Dependency Injection with @Inject and @Named

@Inject
Instead of @Autowired, @javax.inject.Inject may be used as follows:

@Inject
public static HelloWorld getHelloWorld() {
return new HelloWorld("Syed");
}

@Named
Instead of @Component, @javax.inject.Named may be used as follows:

@Named
public class HelloWorld {

public HelloWorld() {

}

Using Collections in spring

Collections can be used in spring by the following way

<bean id="helloWorldService2"
class="com.searchendeca.application.HelloWorld2">
<property name="personMap">
<map>
<entry key="name" value="Syed Ghouse Habib" />
<entry key="age" value="27" />
</map>
</property>
<property name="nameList">
<list>
<value>Syed</value>
<value>Ghouse</value>
</list>
</property>

<property name="nameSet">
<set>
<value>Syed</value>
<value>Ghouse</value>
<value>Syed</value>
<value>Ghouse</value>
</set>
</property>
</bean>

package com.searchendeca.application;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HelloWorld2{
private List<String> nameList= new ArrayList<>();

public List<String> getNameList() {
return nameList;
}

public void setNameList(List<String> nameList) {
this.nameList = nameList;
}

private Map<String,String> personMap= new HashMap<>();

public Map<String, String> getPersonMap() {
return personMap;
}

public void setPersonMap(Map<String, String> personMap) {
this.personMap = personMap;
}

private Set<String> nameSet= new HashSet<>();

public Set<String> getNameSet() {
return nameSet;
}

public void setNameSet(Set<String> nameSet) {
this.nameSet = nameSet;
}

}

Handling Properties in spring

P name space.

P name space is used to define more values for the bean.

Using Properties

<bean id="configBean" class="com.searchendeca.application.PropertiesSample">
<property name="properties">
<props>
<prop key="driverClassName">com.mysql.jdbc.Driver</prop>
</props>
</property>
</bean>

Using <util:properties

<bean id="configBean" class="com.searchendeca.application.PropertiesSample">
<property name="properties" ref="props" />
</bean>
<util:properties id="props">
<prop key="driverClassName">com.mysql.jdbc.Driver</prop>
</util:properties>
package com.searchendeca.application;

import java.util.Properties;


public class PropertiesSample {
   private Properties properties;

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

   public Properties getProperties() {
      return properties;
   }
}

Defining Null Value

<bean class="ExampleBean">
<property name="email">
<null/>
</property>
</bean>

c:nameSpace.

The c: namespace uses the same conventions as the p: one (trailing -ref for bean references) for
setting the constructor arguments by their names.

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="bar" class="x.y.Bar"/>
<bean id="baz" class="x.y.Baz"/>
<!-- traditional declaration -->
<bean id="foo" class="x.y.Foo">
<constructor-arg ref="bar"/>
<constructor-arg ref="baz"/>
<constructor-arg value="foo@bar.com"/>
</bean>
<!-- c-namespace declaration -->
<bean id="foo" class="x.y.Foo" c:bar-ref="bar" c:baz-ref="baz" c:email="foo@bar.com"/>
</beans>

Compound property names

<bean id="Compound" class="com.searchendeca.employee">
<property name="employee.dept.id" value="123" />
</bean>


Using depends on

The depends-on attribute can explicitly force one
or more beans to be initialized before the bean using this element is initialized. The following example
uses the depends-on attribute to express a dependency on a single bean:

<bean id="Helloworld1" class="com.searchendeca.Helloworld1" depends-on="Helloworld"/>
<bean id="Helloworld2" class="com.searchendeca.Helloworld2" />

Lazy-initialized beans
By default, ApplicationContext implementations eagerly create and configure all singleton beans
as part of the initialization process. Generally, this pre-instantiation is desirable, because errors in the
configuration or surrounding environment are discovered immediately, as opposed to hours or even
days later. When this behavior is not desirable, you can prevent pre-instantiation of a singleton bean by marking the bean definition as lazy-initialized. A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup.

<bean id="helloWorldService2"
class="com.searchendeca.application.HelloWorld2" depends-on="configBean" lazy-init="true">

Lifecycle callbacks in Spring

To interact with the container’s management of the bean lifecycle, you can implement
the Spring InitializingBean and DisposableBean interfaces. The container calls
afterPropertiesSet() for the former and destroy() for the latter to allow the bean to perform
certain actions upon initialization and destruction of your beans.

Initialization callbacks

It is recommended that you do not use the InitializingBean interface because it unnecessarily
couples the code to Spring.

hence use the initMethod attribute of @Bean, this will initialize the bean when invoked.

<bean id="helloWorldService"
class="com.searchendeca.application.HelloWorld" autowire = "constructor" scope="singleton" init-method="init" autowire-candidate="false">

</bean>

private String init() {
this.mMessage="Welcome to Search Endeca123";
HelloWorld hello=new HelloWorld();
return hello.getMessage();
}

Destruction callbacks

It is recommended that you do not use the DisposableBean callback interface because it
unnecessarily couples the code to Spring.

Hence With XML-based configuration metadata, you use the destroy-method attribute on the <bean/>

<bean id="helloWorldService"
class="com.searchendeca.application.HelloWorld" autowire = "constructor" scope="singleton" destroy-method="cleanup" autowire-candidate="false">
</bean>

private void cleanup() {
//Some Clean up
}

The presence of the default-init-method attribute on the top-level <beans/> element attribute
causes the Spring IoC container to recognize a method called init on beans as the initialization method callback.When a bean is created and assembled, if the bean class has such a method, it is invoked at the appropriate time.