JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Spring 3 and JSR-330 Annotation : @Named and @Component Difference

November 14, 2013 by Krishna Srinivasan Leave a Comment

@Named and @Component annotations are used for the same purpose. Both the annotations are used for enabling a class to be auto detected as the bean definition for spring’s application context. The following are the main different of these two annotations.

  1. @Named is part of the. Java specification. It is more recommended since this annotation is not tied to spring APIs. If you migrate your applications, you can continue use this annotation.
  2. @Component is part of the spring’s annotations library. It is similar to the @Named annotation in functionality.

[code lang=”java”]
package javabeat.net.core.ioc;

@Named
public class SpringBeanNamed {

}

@Component("beanName")
public class SpringBeanComponent {

}
[/code]

Filed Under: Spring Framework Tagged With: Spring IOC

Bean Definition Inheritance in Spring

November 10, 2013 by Krishna Srinivasan Leave a Comment

In my previous post I have explained how to inherit collection values from the parent bean. Spring offers out of the box support on inheritance for the bean definitions in the XML configuration file. You can define any number of beans and extend them by using the parent  attribute in the bean element. Child bean can inherit all the values, properties, methods, etc. from the parent beans. If you define the same method in the child bean, it simply overrides them in the child bean.

If parent bean have the class definition, then child bean need not define classes, it will use the parent bean. If you want to mention class name for the child bean, then it must have the same properties defined in the parent bean. Because it will try to search for the properties in the parent bean.

The parent bean is declared as abstract in the configuration file, it indicates that Spring container will not create any instance for that bean. If you try to access that bean, it will throw exception. If you don’t use a class type for the parent bean, then declaring it as abstract is mandatory.

Look at the below example. This is very simple example to demonstrate how to use the feature, you could try our more advanced examples and post your comments.

Person.java

[code lang=”java”]
package javabeat.net.core.ioc;

public class Person {
private String name;
private String phone;
private String email;
private String city;
private String country;
public Person(){
System.out.println("Initializing bean…");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String toString(){
StringBuffer buffer = new StringBuffer();
buffer.append("Name : " + this.name);
buffer.append("Phone : " + this.phone);
buffer.append("Email : " + this.email);
buffer.append("City : " + this.city);
buffer.append("Country : " + this.country);
return buffer.toString();
}

}
[/code]

spring-beans-ioc.xml

[code lang=”xml”]
<beans xmlns="http://www.springframework.org/schema/beans"
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-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">

<context:component-scan base-package="javabeat.net.core.ioc"/>
<bean id="personBean" class="javabeat.net.core.ioc.Person" abstract="true">
<property name="name" value="Vijay"/>
<property name="phone" value="678567"/>
<property name="email" value="vijay@javabeat.net"/>
<property name="city" value="Bangalore"/>
<property name="country" value="India"/>
</bean>
<bean id="personBeanSub1" parent="personBean" >
<property name="name" value="Muthu"/>
<property name="phone" value="986756"/>
<property name="email" value="muthu@javabeat.net"/>
</bean>
<bean id="personBeanSub2" parent="personBean">
<property name="name" value="Hari"/>
<property name="phone" value="452345"/>
<property name="email" value="hari@javabeat.net"/>
</bean>
<bean id="personBeanSub3" parent="personBean"/>
</beans>
[/code]

SpringContextLoader.java

[code lang=”java”]
package javabeat.net.core.ioc;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringContextLoader {
public static void main (String args[]){
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("javabeat/net/core/ioc/spring-beans-ioc.xml");
Person child1 = (Person)applicationContext.getBean("personBeanSub1");
Person child2 = (Person)applicationContext.getBean("personBeanSub2");
Person child3 = (Person)applicationContext.getBean("personBeanSub3");
System.out.println(child1.toString());
System.out.println(child2.toString());
System.out.println(child3.toString());
applicationContext.close();
}
}
[/code]

If you run the above example, the result will be:

[code]
Initializing bean…
Initializing bean…
Initializing bean…
Name : MuthuPhone : 986756Email : muthu@javabeat.netCity : BangaloreCountry : India
Name : HariPhone : 452345Email : hari@javabeat.netCity : BangaloreCountry : India
Name : VijayPhone : 678567Email : vijay@javabeat.netCity : BangaloreCountry : India
[/code]

Filed Under: Spring Framework Tagged With: Spring IOC

How to Merge Collections in Spring?

November 9, 2013 by Krishna Srinivasan Leave a Comment

In my previous post I have explained about how to use collections in Spring. This tutorial explains how to merge collections or inherit the values from the parent bean. In some scenarios we need to define a bean as abstract using the abstract=true in the bean definition. It means that another bean definition will be child for this parent bean and will inherit all its properties. This is very useful when we have a common behavior which is used by most of the implementations. In that scenario, spring provides option to merge or inherit the collections which is defined in the parent bean. For example : If you define a List in your parent bean A, another child bean B can point bean A as parent and inherit all the list values defined in that bean.

There are some limitations on merging two collections. We can not merge two different types of collections. For example : we can not merge List and Set. This merging feature is available from Spring 2.0 on wards.

 

Look at the below example :

1. Create a Parent Bean

Company.java

[code lang=”java”]
package javabeat.net.core.ioc;

import java.util.List;

public class Company {
private List<String> employees;

public List<String> getEmployees() {
return employees;
}

public void setEmployees(List<String> employees) {
this.employees = employees;
}
}
[/code]

2. Define Child Bean and Parent Bean in the Spring Configuration

spring-beans-ioc.xml

[code lang=”xml”]
<beans xmlns="http://www.springframework.org/schema/beans"
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-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">

<context:component-scan base-package="javabeat.net.core.ioc"/>
<bean id="companyBean" abstract="true" class="javabeat.net.core.ioc.Company">
<property name="employees">
<list>
<value>Employee 1</value>
<value>Employee 2</value>
</list>
</property>
</bean>
<bean id="companyBeanChild" parent="companyBean">
<property name="employees">
<list merge="true">
<value>Employee 3</value>
<value>Employee 4</value>
</list>
</property>
</bean>
</beans>
[/code]

3. Load Spring Configuration

SpringContextLoader.java

[code lang=”java”]
package javabeat.net.core.ioc;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringContextLoader {
public static void main (String args[]){
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("javabeat/net/core/ioc/spring-beans-ioc.xml");
Company company = (Company)applicationContext.getBean("companyBeanChild");
System.out.println(company.getEmployees());
applicationContext.close();
}
}
[/code]

Filed Under: Spring Framework Tagged With: Spring IOC

Spring Collections Example

November 9, 2013 by Krishna Srinivasan Leave a Comment

This tutorial explains how to use the collections API with Spring configurations. Spring provides out of the box support for all the collections classes like List, Set, Map and Properties for injecting the objects. There is a corresponding elements in the spring configuration file to pass the values to the Java objects. This tutorial passes simple string objects to the collections classes, however you can use the custom objects to store in the collections. Lets look at the example below.

1. Spring Bean and Collections

SpringCollectionsExample.java

[code lang=”java”]
package javabeat.net.core.ioc;

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

public class SpringCollectionsExample {
private List<Object> lists;
private Set<Object> sets;
private Map<Object, Object> maps;
private Properties pros;
public List<Object> getLists() {
return lists;
}
public void setLists(List<Object> lists) {
this.lists = lists;
}
public Set<Object> getSets() {
return sets;
}
public void setSets(Set<Object> sets) {
this.sets = sets;
}
public Map<Object, Object> getMaps() {
return maps;
}
public void setMaps(Map<Object, Object> maps) {
this.maps = maps;
}
public Properties getPros() {
return pros;
}
public void setPros(Properties pros) {
this.pros = pros;
}

}
[/code]

2. Spring Configuration with Collections

spring-beans-ioc.xml

[code lang=”xml”]
<beans xmlns="http://www.springframework.org/schema/beans"
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-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">

<context:component-scan base-package="javabeat.net.core.ioc"/>
<bean id="collectionsExampleBean" class="javabeat.net.core.ioc.SpringCollectionsExample">
<property name="lists">
<list>
<value>List Object 1</value>
<value>List Object 2</value>
</list>
</property>
<property name="sets">
<set>
<value>Set Object 1</value>
<value>Set Object 2</value>
</set>
</property>
<property name="maps">
<map>
<entry key="Key 1" value="Value 1"/>
<entry key="Key 2" value="Value 2"/>
<entry key="Key 3" value="Value 3"/>
</map>
</property>
<property name="pros">
<props>
<prop key="Prop Key 1">Value 1</prop>
<prop key="Prop Key 2">Value 2</prop>
</props>
</property>
</bean>
</beans>
[/code]

3. Spring Context Loader and Access Collections

SpringContextLoader.java

[code lang=”java”]
package javabeat.net.core.ioc;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringContextLoader {
public static void main (String args[]){
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("javabeat/net/core/ioc/spring-beans-ioc.xml");
SpringCollectionsExample collectionsExample = (SpringCollectionsExample)applicationContext.getBean("collectionsExampleBean");
System.out.println(collectionsExample.getLists());
System.out.println(collectionsExample.getSets());
System.out.println(collectionsExample.getMaps());
System.out.println(collectionsExample.getPros());
applicationContext.close();
}
}
[/code]

If you run the application you would see the following result:

[code]
[List Object 1, List Object 2]
[Set Object 1, Set Object 2]
{Key 1=Value 1, Key 2=Value 2, Key 3=Value 3}
{Prop Key 2=Value 2, Prop Key 1=Value 1}
[/code]

If you have any thoughts, please share it in the comments section.

Filed Under: Spring Framework Tagged With: Spring IOC

Circular Dependency in Spring

November 9, 2013 by Krishna Srinivasan Leave a Comment

This tutorial explains one of the basic mistake done by the spring developers while defining the spring beans. Spring will not allow Circular Dependency and will throw an exception (BeanCurrentlyInCreationException) at the time of loading the configuration files. Also it is not good practice to design your project to have the circular dependency. What is circular dependency?. For example : Class A requires an instance of class B through constructor injection, and class B requires an instance of class A through constructor injection. When you try to inject both the beans to each other. spring’s IOC container detects it as circular dependency. Lets look at the below code snippet.

  • Read : Spring Tutorials

ObjA.java

[code lang=”java”]
package javabeat.net.core.ioc;

public class ObjA {
private ObjB b;
public ObjA(ObjB b){
this.b = b;
}
}
[/code]

ObjB.java

[code lang=”java”]
package javabeat.net.core.ioc;

public class ObjB {
private ObjA a;
public ObjB(ObjA a){
this.a = a;
}
}
[/code]

Spring Beans Configuration

[code lang=”xml”]
<context:component-scan base-package="javabeat.net.core.ioc"/>
<bean id="aBean" class="javabeat.net.core.ioc.ObjA">
<constructor-arg ref="bBean"/>
</bean>
<bean id="bBean" class="javabeat.net.core.ioc.ObjB">
<constructor-arg ref="aBean"/>
</bean>
[/code]

SpringContextLoader.java

[code lang=”java”]
package javabeat.net.core.ioc;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringContextLoader {
public static void main (String args[]){
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("javabeat/net/core/ioc/spring-beans-ioc.xml");
applicationContext.close();
}
}
[/code]

When you run the above example, you will get the following exception:

[code]
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name ‘aBean’: Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.
beforeSingletonCreation(DefaultSingletonBeanRegistry.java:327)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.
getSingleton(DefaultSingletonBeanRegistry.java:217)
at org.springframework.beans.factory.support.AbstractBeanFactory.
doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.
getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.
resolveReference(BeanDefinitionValueResolver.java:323)
[/code]

Filed Under: Spring Framework Tagged With: Spring IOC

How to use Initialization callback methods while creating Spring bean?

July 24, 2008 by Krishna Srinivasan Leave a Comment

Initialization callback methods

Springframework provides flexibility to initialize its Beans using the user defined methods. There is some scenario where application developer want to initialize the beans properties after setting all the values. The following example program demonstrates by defining a custom method to initialize the calues.
Spring’s managed bean has to implement InitializingBean from the springframework. This interface declares one method afterPropertiesSet() which has to be overridden by the bean. So, when the bean instance is created, this method also will be called.

also read:

  • Spring Tutorials
  • Spring 4 Tutorials
  • Spring Interview Questions

Though this technique is not recommended. It is easy to directly configure in the xml configuration file with the initialization method name.use init-method=”initialize” to set the value. Look into the following code for more details on implementation.

InitCallBackExample.java

[code lang=”java”]
package javabeat.net.spring.ioc;

import org.springframework.beans.factory.InitializingBean;

/**
* Source : https://javabeat.net
*/

public class Address implements InitializingBean {
public Address(){

}
private String street;
private String city;
private String pincode;

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getPincode() {
return pincode;
}

public void setPincode(String pincode) {
this.pincode = pincode;
}

public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

public void afterPropertiesSet() throws Exception {
System.out.println("After Properties Set Called");
}

}
[/code]

Address.java

[code lang=”java”]
package javabeat.net.spring.ioc;

import org.springframework.beans.factory.InitializingBean;

/**
* Source : https://javabeat.net
*/

public class Address implements InitializingBean {
public Address(){

}
private String street;
private String city;
private String pincode;

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getPincode() {
return pincode;
}

public void setPincode(String pincode) {
this.pincode = pincode;
}

public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

public void afterPropertiesSet() throws Exception {
System.out.println("After Properties Set Called");
}

}[/code]

also read:

  • Spring Books
  • Introduction to Spring Framework
  • Introduction to Spring MVC Framework

applicationContext.xml

[code lang=”xml”]
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="addressBean" class="javabeat.net.spring.ioc.Address"/>
<!–<bean id="addressBean" class="javabeat.net.spring.ioc.Address" init-method="initialize"/>–>
</beans>
[/code]

Filed Under: Spring Framework Tagged With: Spring IOC

Inner beans in Spring IOC

July 21, 2008 by Krishna Srinivasan Leave a Comment

Inner beans

Spring IOC allows Inner Beans declaration. We can declare a bean inside a beans. But, it has few restriction. Inner Beans are like annonymous beans where it is created and used on the fly. this beans cannot be used outside the enclosing beans. So, it is wise to avoid declaring the ‘ID‘ or ‘SCOPE‘ attributes for them. Because, these values will be ignored by the container. Only the enclosing beans can access them.

also read:

  • Spring Tutorials
  • Spring 4 Tutorials
  • Spring Interview Questions

Employee.java

[code lang=”java”]

package javabeat.net.spring.ioc;

/**
* Source : https://javabeat.net
*/

public class Employee {
private String name;
private String empId;
private Address address;
public Employee(){
}

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

public String getEmpId() {
return empId;
}

public void setEmpId(String empId) {
this.empId = empId;
}

public String getName() {
return name;
}

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

[/code]

Address.java

[code lang=”java”]
package javabeat.net.spring.ioc;
/**
* Source : https://javabeat.net
*/

public class Address {
public Address(){

}
private String street;
private String city;
private String pincode;

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getPincode() {
return pincode;
}

public void setPincode(String pincode) {
this.pincode = pincode;
}

public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

}
[/code]

ConstructorInjection.java

[code lang=”java”]
package javabeat.net.spring.ioc;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

/**
* source : www.javabeat.net
*/
public class ConstructorInjection {
public static void main(String args[]){
Resource xmlResource = new FileSystemResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(xmlResource);
Employee employee = (Employee)factory.getBean("employeeBean");
Address address = employee.getAddress();
System.out.println(employee.getName());
System.out.println(employee.getEmpId());
System.out.println(address.getCity());
System.out.println(address.getStreet());
System.out.println(address.getPincode());
}
}
[/code]

applicationContext.xml

[code lang=”xml”]

<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="employeeBean" class="javabeat.net.spring.ioc.Employee">
<property name="name" value="MyName"/>
<property name="empId" value="001"/>
<property name="address">
<bean class="javabeat.net.spring.ioc.Address">
<property name="street">
<value>Street</value>
</property>
<property name="city">
<value>Bangalore</value>
</property>
<property name="pincode">
<value>567456</value>
</property>
</bean>
</property>
</bean>
</beans>
[/code]

also read:

  • Spring Books
  • Introduction to Spring Framework
  • Introduction to Spring MVC Framework

Filed Under: Spring Framework Tagged With: Spring IOC

Setter Injection in Spring IOC

July 21, 2008 by Krishna Srinivasan Leave a Comment

Setter Injection

This article presents how to write the Setter Injection in Spring IOC. There are two types of Dependency Injection(DI) techniques we can use. 1) Setter Injection and 2) Constructor Injection.

also read:

  • Spring Tutorials
  • Spring 4 Tutorials
  • Spring Interview Questions

As the name implies, using setter methods in a bean class the Spring IOC container will inject the dependencies. This technique is considered as the best approach for Dependency Injection. In this type of injection we have chance to reconfigure the bean instance as needed basis.

Employee.java

[code lang=”java”]
<code>
package javabeat.net.spring.ioc;

/**
* Source : https://javabeat.net
*/

public class Employee {
private String name;
private String empId;
private Address address;
public Employee(){
}

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

public String getEmpId() {
return empId;
}

public void setEmpId(String empId) {
this.empId = empId;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}
[/code]

Address.java

[code lang=”java”]
package javabeat.net.spring.ioc;
/**
* Source : https://javabeat.net
*/

public class Address {
public Address(){

}
private String street;
private String city;
private String pincode;

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getPincode() {
return pincode;
}

public void setPincode(String pincode) {
this.pincode = pincode;
}

public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

}[/code]

ConstructorInjection.java

[code lang=”java”]
package javabeat.net.spring.ioc;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

/**
* source : www.javabeat.net
*/
public class ConstructorInjection {
public static void main(String args[]){
Resource xmlResource = new FileSystemResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(xmlResource);
Employee employee = (Employee)factory.getBean("employeeBean");
Address address = employee.getAddress();
System.out.println(employee.getName());
System.out.println(employee.getEmpId());
System.out.println(address.getCity());
System.out.println(address.getStreet());
System.out.println(address.getPincode());
}
}[/code]

applicationContext.xml

also read:

  • Spring Books
  • Introduction to Spring Framework
  • Introduction to Spring MVC Framework

[code lang=”xml”]
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="addressBean" class="javabeat.net.spring.ioc.Address">
<property name="street">
<value>Street</value>
</property>
<property name="city">
<value>Bangalore</value>
</property>
<property name="pincode">
<value>567456</value>
</property>
</bean>
<bean id="employeeBean" class="javabeat.net.spring.ioc.Employee">
<property name="name" value="MyName"/>
<property name="empId" value="001"/>
<property name="address" ref="addressBean"/>
</bean>
</beans>[/code]

Filed Under: Spring Framework Tagged With: Spring IOC

Constructor Injection in Spring IOC

July 21, 2008 by Krishna Srinivasan Leave a Comment

Constructor Injection

This article presents how to write the Constructor Injection in Spring IOC. There is two types of Dependency Injection(DI) techniques we can use. 1) Setter Injection and 2) Constructor Injection.

also read:

  • Spring Tutorials
  • Spring 4 Tutorials
  • Spring Interview Questions

As the name implies, using constructor the Spring IOC container will inject the dependencies. The constructor will take arguments based on number of dependencies required. This is one of the drawback using Constructor based DI. You don’t have option to reconfigure the dependencies at later point of time, since all the dependencies are resolved only at the time of invoking the constructor. if you don’t have requirement to inject all the dependencies, please use Setter Injection technique to obtain the more flexibilty on configuring beans.

[code lang=”java”]
<constructor-arg index="0" type="java.lang.String" value="MyName"/>
[/code]

The above code is an example for how to pass dependency arguments to the constructor. Index attribute is useful when you have
multiple arguments with the same type, you can inform the IOC container about the order of the arguments. You can pass bean reference
using the ref element.

Employee.java

[code lang=”java”]
package javabeat.net.spring.ioc;

/**
* Source : https://javabeat.net
*/

public class Employee {
private String name;
private String empId;
private Address address;
public Employee(String name, String empId, Address address){
this.name = name;
this.empId = empId;
this.address = address;
}

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

public String getEmpId() {
return empId;
}

public void setEmpId(String empId) {
this.empId = empId;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}
[/code]

Address.java

[code lang=”java”]
package javabeat.net.spring.ioc;
/**
* Source : https://javabeat.net
*/

public class Address {
public Address(){

}
private String street;
private String city;
private String pincode;

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getPincode() {
return pincode;
}

public void setPincode(String pincode) {
this.pincode = pincode;
}

public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

}
[/code]

ConstructorInjection.java

[code lang=”java”]
package javabeat.net.spring.ioc;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

/**
* source : www.javabeat.net
*/
public class ConstructorInjection {
public static void main(String args[]){
Resource xmlResource = new FileSystemResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(xmlResource);
Employee employee = (Employee)factory.getBean("employeeBean");
Address address = employee.getAddress();
System.out.println(employee.getName());
System.out.println(employee.getEmpId());
System.out.println(address.getCity());
System.out.println(address.getStreet());
System.out.println(address.getPincode());
}
}
[/code]

also read:

  • Spring Books
  • Introduction to Spring Framework
  • Introduction to Spring MVC Framework

applicationContext.xml

[code lang=”xml”]
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="addressBean" class="javabeat.net.spring.ioc.Address">
<property name="street">
<value>Street</value>
</property>
<property name="city">
<value>Bangalore</value>
</property>
<property name="pincode">
<value>567456</value>
</property>
</bean>
<bean id="employeeBean" class="javabeat.net.spring.ioc.Employee">
<constructor-arg index="0" type="java.lang.String" value="MyName"/>
<constructor-arg index="1" type="java.lang.String" value="001"/>
<constructor-arg index="2">
<ref bean="addressBean"/>
</constructor-arg>
</bean>
</beans>[/code]

Filed Under: Spring Framework Tagged With: Spring IOC

Simple example for Before advice and After Advice in Spring Framework

July 14, 2008 by Krishna Srinivasan Leave a Comment

BeforeAdvice and AfterReturningAdvice

This tips presents a very simple program for invoking the Before Advice and After Returning Advice in the Spring Framework. Thsese two methods are part of Spring’s AOP implementation and used as interceptor methods. the following program create spring beans using the standalone java program and invokes the business logic method.
Business logic method is surrounded by Before Advice and After Returning Advice method. It is configured in thespring’s configuration xml file. When ever any client invokes that particular method, the advices will be called to perform a certain operations. Normally these kind of techniques used for printing the debug messages while invoking the methods.

also read:

  • Spring Tutorials
  • Spring 4 Tutorials
  • Spring Interview Questions

SpringAopMain.java

[code lang=”java”]
package javabeat.net.spring.aop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

/**
* source : www.javabeat.net
*/
public class SpringAopMain {
public static void main(String[] args) {
// Read the configuration file
ApplicationContext ctx = new FileSystemXmlApplicationContext(
"spring-config.xml");

// Instantiate an object
BusinessInterface businessInterface = (BusinessInterface) ctx
.getBean("businesslogicbean");

// Execute the public method of the bean
businessInterface.businessLogicMethod();
}
}
[/code]

BusinessInterface.java

[code lang=”java”]
package javabeat.net.spring.aop;

/**
* source : www.javabeat.net
*/
public interface BusinessInterface {
void businessLogicMethod();
}
[/code]

BusinessInterfaceImpl.java

[code lang=”java”]
package javabeat.net.spring.aop;

/**
* source : www.javabeat.net
*/
public class BusinessInterfaceImpl implements BusinessInterface{
public void businessLogicMethod() {
System.out.println("BusinessLogic Method Called");
}
}
[/code]

BeforeAdviceExample.java

[code lang=”java”]
package javabeat.net.spring.aop;
import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

/**
* source : www.javabeat.net
*/
public class BeforeAdviceExample implements MethodBeforeAdvice {
public void before(Method arg0, Object[] arg1, Object arg2)
throws Throwable {
System.out.println("Before Advice Called");
}
}
[/code]

AfterAdviceExample.java

[code lang=”java”]
package javabeat.net.spring.aop;

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;

/**
* source : www.javabeat.net
*/
public class AfterAdviceExample implements AfterReturningAdvice {
public void afterReturning(Object arg0, Method arg1, Object[] arg2,
Object arg3) throws Throwable {
System.out.println("After Advice Called");
}
}
[/code]

spring-config.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC
"-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

<!– Bean configuration –>
<bean id="businesslogicbean"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>javabeat.net.spring.aop.BusinessInterface</value>
</property>
<property name="target">
<ref local="beanTarget" />
</property>
<property name="interceptorNames">
<list>
<value>theTracingBeforeAdvisor</value>
<value>theTracingAfterAdvisor</value>
</list>
</property>
</bean>

<!– Bean Classes –>
<bean id="beanTarget" class="javabeat.net.spring.aop.BusinessInterfaceImpl" />

<!– Advisor pointcut definition for before advice –>
<bean id="theTracingBeforeAdvisor"
class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref local="theTracingBeforeAdvice" />
</property>
<property name="pattern">
<value>.*</value>
</property>
</bean>

<!– Advisor pointcut definition for before advice –>
<bean id="theTracingAfterAdvisor"
class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref local="theTracingAfterAdvice" />
</property>
<property name="pattern">
<value>.*</value>
</property>
</bean>

<!– Advice classes –>
<bean id="theTracingBeforeAdvice"
class="javabeat.net.spring.aop.BeforeAdviceExample" />
<bean id="theTracingAfterAdvice"
class="javabeat.net.spring.aop.AfterAdviceExample" />

</beans>[/code]

also read:

  • Spring Books
  • Introduction to Spring Framework
  • Introduction to Spring MVC Framework

Filed Under: Spring Framework Tagged With: Spring IOC

  • 1
  • 2
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved