Spring lazy-init Example

lazy-init is the same concept of lazy loading and it is one of the attribute of bean, either this can be true or false.In this example we are going to test both scenarios
lazy-init=true (Bean will initialized when a request is received)
lazy-init=false(Bean will initialized with spring container initialization

1. Create two sample beans (First.java, Second.java)

package com.pretech; 
public class First { 
	public First() {
		System.out.println("Class First is initialized");
	}
}
package com.pretech; 
public class Second { 
	public Second() {
		System.out.println("Class Second Initialized");
	} 
}

Create spring configuration xml file with lazy-init attribute (spring-lazy.xml)

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<beanid="first"class="com.pretech.First"lazy-init="false"/>
<beanid="second"class="com.pretech.Second"lazy-init="true"/>
</beans>

Create a Main class to test lazy-init

package com.pretech; 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; 
public class SpringLazyInitTest { 
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("spring-lazy.xml");
		System.out.println("Calling Second Bean");
		context.getBean("second");
	} 
}

Output


Below output we can see class First is initialized during Spring container start up and Class second is initialized upon the the request

Class First is initialized
Calling Second Bean
Class Second Initialized

Spring Automatically Detecting classes using @Repository Example

In Spring automatically detecting classes are @Repository, @Service, and @Controller. In this example using @Repository annotations in side bean and adding component scane in spring configuration xml file. In Persistence layer ,@Repository supports as a marker for automatic exception translation.

Create a Bean with @Repository

package com.pretech;
import org.springframework.stereotype.Repository;
@Repository("repo")
public class Employee {
	public String getName() {
		return"Vinod";
	}
	public String getAddress() {
		return"bangalore";
	}
}

Update component scan details in spring configuration file (SpringContext.xml)

<?xml version="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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">
<context:component-scanbase-package="com.pretech"/>
</beans> 

Create a Main class to test @Repository

package com.pretech;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; 
public class RepositoryTest { 
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("SpringContext.xml");
		Employee emp =(Employee) context.getBean("repo");
		System.out.println(emp.getName());
		System.out.println(emp.getAddress());
	}
}

Ouput


Vinod
bangalore

Spring Disposable Bean Example

Disposable Bean is used to do some closing/destructive task before destroying bean. It is same destroy method in Bean life cycle Bean life cycle methods

Create a Java class

Create java class which implements Disposable Bean interface and implement destroy method. In this method we can add all our closing or destructive tasks

package com.pretech; 
importorg.springframework.beans.factory.DisposableBean; 
public class ClosingBean implements DisposableBean 
{
	public void destroy() {
		System.out.println("doing all close activities");
	}
}

Add bean details into spring configuration (SpringConfig.xml)

<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-3.0.xsd ">
<beanid="dBean"class="com.pretech.ClosingBean"/>
</beans>

Create a main class to test DisposableBean

package com.pretech; 
importorg.springframework.context.support.AbstractApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext; 
public class DisposableBeanTest { 
	public static void main(String[] args) {
		AbstractApplicationContext context = newClassPathXmlApplicationContext("SpringConfig.xml");
		context.registerShutdownHook();
	} 
}

output



doing all close activities

Spring Annotation based Bean configuration Example (@Bean)

In spring we can use @Bean annotations to create Bean. Here is one example which is using @Configuration and @Bean to create Beans without any xml configuration.

Software Used

Java 1.7
Spring 3 jars
Apache Common logging jars
Cglib2 jars

Create a bean class (Student.java)

package com.pretech; 
public class Student {
	privateString name;
	privateString address; 
	publicString getName() {
		returnname;
	} 
	publicvoidsetName(String name) {
		this.name= name;
	} 
	publicString getAddress() {
		returnaddress;
	} 
	publicvoidsetAddress(String address) {
		this.address= address;
	} 
}

Create a Bean configuration class

package com.pretech; 
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration; 
@Configuration
public class BeanConfig {
	@Bean
	publicStudent getStudentBean() {
		Student s = newStudent();
		s.setName("Vinod");
		s.setAddress("Bangalore");
		returns;
	}
}

Create a main class to test bean

package com.pretech; 
importorg.springframework.context.annotation.AnnotationConfigApplicationContext; 
public class Main { 
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = newAnnotationConfigApplicationContext();
		context.register(BeanConfig.class);
		context.refresh();
		Student student = context.getBean(Student.class);
		System.out.println(student.getName());
		System.out.println(student.getAddress());
	} 
}

Output



Vinod


Bangalore

Apache Camel + Spring +Activemq Example

In the previous example (Apache Camel + Activemq) we created Camel Router class manually and started Camel to route messages from one queue to another queue. In this example you will see how to configure Camel Routing in Spring configuration xml file.
 

Goals

1. Start Activemq message broker

2. Setup Camel+Spring project

3. Create Spring configuration file

4. Main program to execute Camel

1. Setup Activemq 

1. Download activemq from http://activemq.apache.org/download-archives.html

2. Extract activemq zip file and start ActiveMQ (Click on activemq.bat file for windows)
 
3. Check activemq console using http://localhost:8161/admin  (Use default credentials admin/admin to login)
 

2. Setup Camel + Spring Project

Create a maven project and add below dependencies
 
 
<dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-core</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-spring</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-camel</artifactId>
            <version>5.10.0</version>
        </dependency>
       
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>
 
 

3. Create Spring configuration file (camel-application-context.xml)

 
In this file we are using the message routing using spring DSL and creating the beans for camel producer template and kms components.
 
<?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:camel="http://camel.apache.org/schema/spring"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

    <camelContext xmlns="http://camel.apache.org/schema/spring">
        <route>
            <from uri="jms:queue:testQSource" />
            <to uri="jms:queue:testQDestination" />
        </route>
    </camelContext>
    <camel:camelContext id="camel-client">
        <camel:template id="camelTemplate" />
    </camel:camelContext>
    <bean id="jms" class="org.apache.activemq.camel.component.ActiveMQComponent">
        <property name="brokerURL" value="tcp://localhost:61616" />
    </bean>
</beans>
 
 

4. Main program to send message

Here we will load the above defined spring configuration and use the Camel producer template to sending the messages, once the message is reached in the queue , the above routes which is defined in the xml file will start consuming and processing .

 
package com.vinod.test;
import org.apache.camel.ProducerTemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestCamelSpring {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("camel-application-context.xml");
        ProducerTemplate camelTemplate = context.getBean("camelTemplate", ProducerTemplate.class);
        System.out.println("Message Sending started");
        camelTemplate.sendBody("jms:queue:testQSource","Sample Message");
        System.out.println("Message sent");
    }

}
  

5. Output

Run the program and see below output in the console and in the Activemq we can see new queues are created and routed the messages

Console

Message Sending started

Message sent


image

Download example

https://github.com/kkvinodkumaran/camel

Reference

Apache Camel + ActiveMQ Example

Apache Camel

Apache Camel is a simple routing engine which provides the implementation of Enterprise Integration Pattern using Java or other Domain specific language. See more about  Apache Camel  and Enterprise Integration Patterns. In this example we are going to create a Message producer class to push messages in to ActiveMQ messaging system and Creating a simple Router to copy all messages from one Queue to another Queue upon starting Camel Context.

Goals

Setup ActiveMQ 

Create a JMS Message Producer to send messages

Create a Camel Router and Start Camel context to Route Messages

Note: In this example we are not using any spring apis

Setup ActiveMQ Messaging System

1. Download activemq from http://activemq.apache.org/download-archives.html

2. Extract activemq zip file and start ActiveMQ (Click on activemq.bat file)

3. Check activemq console using http://localhost:8161/admin  (Use default credentials admin/admin to login)

Create a Message Producer to send Messages


package com.vinod.test;

import javax.jms.ConnectionFactory;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class MessageProducerExample {
    public static void main(String[] args) {
        try {

            // Create a ConnectionFactory

            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "admin",
                    ActiveMQConnection.DEFAULT_BROKER_URL);

            // Create a Connection

            Connection connection = connectionFactory.createConnection();

            connection.start();

            // Create a Session

            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            // Create the destination

            Destination destination = session.createQueue("testMQ");

            // Create a MessageProducer from the Session to the Queue

            MessageProducer producer = session.createProducer(destination);

            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

            // Create a messages

            TextMessage message = session.createTextMessage("Helloworld");

            //sending message
            producer.send(message);
            session.close();
            connection.close();

            System.out.println("Message sent");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
 

 

Run Message Producer and check the Queue

Run the above program and see messages are going to the activemq, it provides the console to see the message details

(http://localhost:8161/admin)


image

 

Create a Camel class to route messages

Here we are just consuming the above message and putting in to another queue

 

package com.vinod.test;

import javax.jms.ConnectionFactory;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jms.JmsComponent;
import org.apache.camel.impl.DefaultCamelContext;

public class CamelActiveMQExample {
    public static void main(String[] args) {
        try {
            CamelContext context = new DefaultCamelContext();
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "admin",
                    ActiveMQConnection.DEFAULT_BROKER_URL);
            context.addComponent("test-jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
            context.addRoutes(new RouteBuilder() {
                public void configure() {
                    from("test-jms:queue:testMQ").log("${body}").to("test-jms:queue:testMQDestination");
                }
            });
            context.start();
            Thread.sleep(1000);
            context.stop();
            System.out.println("Done");
        } catch (Exception e) {

            e.printStackTrace();
        }

    }

}
 
 

Run Camel route

Now we can check the ActiveMQ console and see new Queue has been created and all the messages are moved from testMQ to testMQDestination queue


image

Reference

Apache Camel

Done!!! 

Download example

https://github.com/kkvinodkumaran/camel

Apache Camel Simple Routing Example

Apache Camel

Apache Camel is a simple routing engine which provides the implementation of Enterprise Integration Pattern using Java or other Domain specific language. See more about  Apache Camel  and Enterprise Integration Patterns. In this example we are going to create a simple Router to copy files from one directory to another directory upon starting Camel Context.

Environment Setup

Create a maven project and add below dependency
<dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-core</artifactId>
            <version>2.12.1</version>
        </dependency>
Create a Java class to implement Router and start Camel
package com.vinod.test;

import java.io.File;

import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

public class CamelSimpleRouteExample {

    public static void main(String[] args) {
        try {
            CamelContext context = new DefaultCamelContext();
            context.addRoutes(new RouteBuilder() {
                public void configure() {
                    from("file://source").to("file://destination");
                }
            });
            context.start();
            File ff = new File("source//Temp.txt");
            ff.createNewFile();
            Thread.sleep(1000);
            context.stop();
            System.out.println("Done");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
Run it...
After running this program we can see the default source and destination directories are created and transferring the Temp.txt in to destination folder.

Download example
https://github.com/kkvinodkumaran/camel

Reference


Apache Camel

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts