Similarities: Both StringBuilder and StringBuffer are mutable. That means you can change the content of them, with in the same location.

Differences: StringBuffer is mutable and synchronized as well. Where as StringBuilder is mutable but not synchronized by default.

Meaning of synchronized (synchronization): When some thing is synchronized, then multiple threads can access, and modify it with out any problem or side effect. StringBuffer is synchronized, so you can use it with multiple threads with out any problem.

Which one to use when? StringBuilder : When you need a string, which can be modifiable, and only one thread is accessing and modifying it. StringBuffer : When you need a string, which can be modifiable, and multiple threads are accessing and modifying it.

Note : Don’t use StringBuffer unnecessarily, i.e., don’t use it if only one thread is modifying and accessing it because it has lot of locking and unlocking code for synchronization which will unnecessarily take up CPU time. Don’t use locks unless it is required.

Simply use StringBuilder unless you really are trying to share a buffer between threads. StringBuilder is the unsynchronized (less overhead = more efficient)

When a String is there and you add use concat like one below

  
 String x = "Java";
 x.concat("Rules !");
 sysout(x);

Now in the above there would be 2 string object created with output Java.When you used append in stringBuilder or stringBuffer the changes were applied over the object itself

  
 StringBuiler x = new StringBuiler("Java");
 x.append("Rules !");
 sysout(x);

the output would be Java Rules !

I will give you an example first:

public interface LoginAuth{
   public String encryptPassword(String pass);
   public void checkDBforUser();
}

Now suppose you have 3 databases in your application. Then each and every implementation for that database needs to define the above 2 methods:

public class DBMySQL implements LoginAuth{
          // Needs to implement both methods
}
public class DBOracle implements LoginAuth{
          // Needs to implement both methods
}
public class DBAbc implements LoginAuth{
          // Needs to implement both methods
}

But what if encryptPassword() is not database dependent, and it’s the same for each class? Then the above would not be a good approach.

Instead, consider this approach:

public abstract class LoginAuth{
   public String encryptPassword(String pass){
            // Implement the same default behavior here 
            // that is shared by all subclasses.
   }

   // Each subclass needs to provide their own implementation of this only:
   public abstract void checkDBforUser();
}

Now in each child class, we only need to implement one method – the method that is database dependent.

Technical Differences

  1. Implementing an interface consumes very little CPU, because it’s not a class, just a bunch of names, and therefore there is no expensive look-up to do. It’s great when it matters such as in embedded devices
  2. Abstract classes, unlike interfaces, are classes. They are more expensive to use because there is a look-up to do when you inherit from them.
  3. Abstract classes can have constants, members, method stubs (methods without a body) and defined methods, whereas interfaces can only have constants and methods stubs.
  4. Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public (they are defined public by default).
  5. When inheriting an abstract class, a concrete child class must define the abstract methods, whereas an an abstract class can extend another abstract class and abstract methods from the parent class don’t have to be defined.
  6. Similarly, an interface extending another interface is not responsible for implementing methods from the parent interface. This is because interfaces cannot define any implementation.
  7. A child class can only extend a single class (abstract or concrete), whereas an interface can extend or a class can implement multiple other interfaces.
  8. A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility (public).

Consider using abstract classes if :
You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
You want to declare non-static or non-final fields.

Consider using interfaces if :

You expect that unrelated classes would implement your interface. For example,many unrelated objects can implement Serializable interface.
You want to specify the behaviour of a particular data type, but not concerned about who implements its behaviour.
You want to take advantage of multiple inheritance of type.

abstract class establishes “is a” relation with concrete classes. interface provides “has a” capability for classes.

dispatcher-servlet.xml

 <mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>

HomeController.java

package com.mugil.controls;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HomeController {	
	@RequestMapping("/home")	
	public String testMethod()
	{
		return "home";
	}
}

style.css

h1
{
  color : red;
}

DAOService.java

public class DAOService 
{
	private List<Person> arrPersons = new ArrayList<Person>(); 
			
	public DAOService()
	{
		
		Person objPerson = new Person();
		objPerson.setName("Person 1");
		objPerson.setLocation("Teynampet");
		
		arrPersons.add(objPerson);
		
		Person objPerson2 = new Person();
		objPerson2.setName("Person 2");
		objPerson2.setLocation("TNagar");
		
		arrPersons.add(objPerson2);
	}

	public List getList()
	{
		return this.arrPersons;
	}
}

ListPerson.java

@Controller
@RequestMapping("/List")
public class ListPerson 
{	
	@Autowired
	private DAOService objDAOService;
	
	@RequestMapping("/PersonList")
	public String listPersons(Model model)
	{
		DAOService objDAOService = new DAOService();
		
		model.addAttribute("personList", this.objDAOService.getList());
		
		return "display_list";
	}
}

display_list.jsp

<title>Insert title here</title>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
</head>
<body>	
	<table>
		<c:forEach items="${personList}" var="objPerson"> 
			<tr>
				<td>${objPerson.name}</td>
				<td>${objPerson.location}</td>
			</tr>
		</c:forEach>
	</table>
</body>

applicationContext.xml

<bean name="DAOService" class="com.mugil.controls.DAOService"></bean>

pom.xml

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

Method Arguments in Controller

@Controller
@RequestMapping("/Control1")
public class TestController 
{	
	@RequestMapping("/Control2")		
	public String TestMe(HttpSession session, HttpServletRequest request)
	{
		request.setAttribute("name", "Mugil Vannan");
		session.setAttribute("Test", "TestValue");
		System.out.println("1");
		return "hello";
	}
	
	@RequestMapping(value="/Control2", method=RequestMethod.POST)
	public String TestMe2(HttpSession session, HttpServletRequest request)
	{
		System.out.println(session.getAttribute("Test"));
		System.out.println(request.getParameter("cboArea"));		
		return "display";
	}
}

Alternate of HttpServletRequest request

@RequestMapping(value="/Control2", method=RequestMethod.POST)
public String TestMe2(HttpSession session, @RequestParam("cboArea") String Area)
{
  System.out.println(session.getAttribute("Test"));
  System.out.println(Area);		
  return "display";
}

Loggable.java

package com.mugil.shapes;
public @interface Loggable {
}

.java

@Aspect
public class LoggingAspect 
{
@Around("@annotation(com.mugil.shapes.Loggable)")
	public void LoggingAdvice2(ProceedingJoinPoint pjp)
	{
		Object objObject = null;		
		
		try {
			System.out.println("Code before Method Execution Goes here");			
			objObject = pjp.proceed();
			System.out.println("Code after Method Execution Goes here");
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

Triangle.xml

public class Triangle 
{
   private String name;

   @Loggable
   public String getName() 
   {
     return name;
   }
.
.
}
Posted in AOP.

spring.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

	<aop:aspectj-autoproxy />
        <bean id="customerBo" class="CustomerBoImpl" />
	<bean name="objTriangle" class="com.mugil.shapes.Triangle">
         	<property name="name" value="Triangle Name"></property>
        </bean>
        <bean name="objCircle" class="com.mugil.shapes.Circle">
    	        <property name="name" value="Circle Name"></property>
        </bean>
        <bean id="shapeService" class="com.mugil.shapes.ShapeService" autowire="byName"/>    	
        <bean name="loggingAspect" class="com.mugil.shapes.LoggingAspect"/>
          <aop:config>
    	     <aop:aspect id="loggingAspect" ref="loggingAspect">
    		<aop:pointcut expression="execution(* com.mugil.shapes.*.get*())" id="allGetters"/>
    		<aop:around method="LoggingAdvice2" pointcut-ref="allGetters"/>
    	     </aop:aspect>
          </aop:config>
</beans>

spring.xml

<aop:aspect id="loggingAspect" ref="loggingAspect">

equivalent to

@Aspect
public class LoggingAspect {

spring.xml

<aop:pointcut expression="execution(* com.mugil.shapes.*.get*())" id="allGetters"/>

equivalent to

@Pointcut("execution(* com.mugil.shapes.*.get*())")
public void allGetters()
{	 
}

spring.xml

<aop:around method="LoggingAdvice2" pointcut-ref="allGetters"/>

equivalent to

@Around("allGetters()")
public void LoggingAdvice2(ProceedingJoinPoint pjp)
{
.
.

<aop:pointcut expression="execution(* com.mugil.shapes.*.get*())" id="allGetters"/>
<aop:around method="LoggingAdvice2" pointcut-ref="allGetters"/>

could be replaced using pointCut

<aop:around method="LoggingAdvice2" pointcut="execution(* com.mugil.shapes.*.get*())"/>
Posted in AOP.

Aspect Oriented Programming answers cross-cutting concern.Cross-cutting concern is one that can affect the whole application and should be centralized in one location in code as possible, such as transaction management, authentication, logging, security etc.

Aspect – A module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement.

Advice – This is the actual action to be taken either before or after the method execution. This is actual piece of code that is invoked during program execution by Spring AOP framework.

LoggingAspect.java

package com.mugil.shapes;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoggingAspect 
{
	@Before("execution(public String getName())")
	public void loggingAdvice()
	{
		System.out.println("This is Logging Advice");
	}
}

DrawingApp.java

package com.mugil.shapes;

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

public class DrawingApp 
{
	public static void main(String[] args) 
	{
		ApplicationContext objContext = new ClassPathXmlApplicationContext("Spring-Customer.xml");
		ShapeService  objCircle = (ShapeService) objContext.getBean("shapeService", ShapeService.class);
		System.out.println(objCircle.getObjCircle().getName());
System.out.println(objCircle.getObjTriangle().getName());
	}
}

Circle.java

package com.mugil.shapes;

public class Circle {
	private String name;

	public String getName() {
		return name;
	}

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

Triangle.java

package com.mugil.shapes;

public class Triangle {
	private String name;

	public String getName() {
		return name;
	}

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

Output

This is Logging Advice
Circle Name
This is Logging Advice
Triangle Name

@Before(“execution(public String getName())”)
Applies for all the methods with getName() signature (Triangle and Circle Class)

Output

This is Logging Advice
Circle Name
This is Logging Advice
Triangle Name

@Before(“execution(public String com.mugil.shapes.Circle.getName())”)
Applies for the methods with getName() signature (Circle Class)

Output

This is Logging Advice
Circle Name

@Before(“execution(public String com.mugil.shapes.*.getName())”)
Applies for getName() method in Triangle and Circle Class

Output

This is Logging Advice
Circle Name
This is Logging Advice
Triangle Name

@Before(“execution(public * get*())”)
Applies for all getters method in Triangle,Circle and ShapeService Class

Output

This is Logging Advice
This is Logging Advice
Circle Name
This is Logging Advice
This is Logging Advice
Triangle Name

@Before(“execution(public String getName(*))”)
Applies to all getName() method with one or more argument.

@Before(“execution(public String getName(..))”)
Applies to all getName() method with zero or more argument.

Pointcut – This is a set of one or more joinpoints where an advice should be executed. You can specify pointcuts using expressions or patterns as we will see in our AOP examples.

DrawingApp.java

package com.mugil.shapes;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class LoggingAspect 
{	
	@Before("allGetters()")
	public void loggingAdvice1()
	{
		System.out.println("This is Logging Advice 1");
	}
	
	@Before("allGetters()")
	public void loggingAdvice2()
	{
		System.out.println("This is Logging Advice 2");
	}
		
	@Pointcut("execution(* getName())")
	public void allGetters()
	{	
	}
}
  1. allGetters() method will be called when ever the getName() method of Circle (or) Triangle gets called
  2. Before allGetters() method gets called the loggingAdvice1() and loggingAdvice2() method gets called.

Output

This is Logging Advice 1
This is Logging Advice 2
Circle Name
 @Pointcut("execution(* com.mugil.shapes.*.get*(..))")

Applies for all the Getters within shapes package

 @Pointcut("execution(public * com.mugil.shapes.*.get*(..))")

Applies for all the Public Getters within shapes package

 @Pointcut("within(com.mugil.shapes.*)")

within applies for everything within class whereas execution applies only to the methods.

Runs for all methods getters and setters in com.mugil.shapes.* package.

@Pointcut("args(..)")

Runs for all methods getters and setters.

Join point – This represents a point in your application where you can plug-in AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework.

Using JoinPoint we can have access to the Object in the advice method.

LoggingAspect.java

package com.mugil.shapes;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class LoggingAspect {
	
	@Before("allGetters()")
	 public void LogginAdvice(JoinPoint joinpoint)
    {
		System.out.println("advice is run");
	    System.out.println(joinpoint.toString());
    }
	
	@Before("args(name)")
	public void LoggingAdvice2(String name)
	{
		System.out.println("-- " + name);
	}
	
	@Pointcut("execution(* com.mugil.shapes.*.get*())")
	public void allGetters()
	{	
	}
}

DrawingApp.java

public class DrawingApp {
	public static void main(String[] args) {
		ApplicationContext objContext = new ClassPathXmlApplicationContext("Spring-Customer.xml");
		ShapeService  objCircle = (ShapeService) objContext.getBean("shapeService", ShapeService.class);
objCircle.getObjTriangle().setName("Test Tri");
		System.out.println(objCircle.getObjTriangle().getName());	
	}
}

Output

advice is run
execution(Triangle com.mugil.shapes.ShapeService.getObjTriangle())
-- Test Tri
advice is run
execution(Triangle com.mugil.shapes.ShapeService.getObjTriangle())
advice is run
execution(String com.mugil.shapes.Triangle.getName())
Test Tri

LoggingAspect.java

@Aspect
public class LoggingAspect {
	
	@Before("allGetters()")
	 public void LogginAdvice(JoinPoint joinpoint)
    {
		System.out.println("advice is run");
	    System.out.println(joinpoint.toString());
    }
	
	@AfterReturning(pointcut ="args(name)", returning="returnString")
	public void LoggingAdvice2(String name, String returnString)
	{
		System.out.println("This is Input to Method " + name);
		System.out.println("This is Returned  from  Method " + returnString);
	}
	
	@AfterThrowing(pointcut="args(name)", throwing="ex")
	public void LoggingAdvice4(String name, RuntimeException ex)
	{
		System.out.println("This will be Printed incase of Exception is Thrown in Method");		
		System.out.println(ex);
	}

	
	@Pointcut("execution(* com.mugil.shapes.*.get*())")
	public void allGetters()
	{	
	}
}

Using Around

@Around("allGetters()")
	public void LoggingAdvice2(ProceedingJoinPoint pjp)
	{
		Object objObject = null;		
		
		try {
			System.out.println("Code before Method Execution Goes here");			
			objObject = pjp.proceed();
			System.out.println("Code after Method Execution Goes here");
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
Posted in AOP.

Event Handling requires 3 Things

  1. Event Publisher
  2. Event Listener
  3. Event

CustomEvent.java(Event)

import org.springframework.context.ApplicationEvent;

public class CustomEvent extends ApplicationEvent
{
	public CustomEvent(Object source) 
        {
		super(source);
	}	

	public String toString()
	{
		return "Custom Message from Custom Event";
	}
}

CustomEventListener.java(Event Listener)

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class CustomEventListener implements ApplicationListener
{
	@Override
	public void onApplicationEvent(ApplicationEvent event) {		
		System.out.println(event.toString());
	}
}

Circle.java(Event Publisher)

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;

@Component
public class Circle implements Shape, ApplicationEventPublisherAware
{			
	private ApplicationEventPublisher publisher;
	
	@Override
	public void drawShape() {	
		CustomEvent objCustEvent = new CustomEvent(this); 
		publisher.publishEvent(objCustEvent);
	}
	
	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
		this.publisher = publisher;
	}

	public ApplicationEventPublisher getPublisher() {
		return publisher;
	}

	public void setPublisher(ApplicationEventPublisher publisher) {
		this.publisher = publisher;
	}	
}	

Java Specification Request JSR 250

spring.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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-2.5.xsd">	
	<bean id="pointC" class="com.mugil.shapes.Point">
		<property name="x" value="20"/>
		<property name="y" value="0"/>
	</bean> 	
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="constant.properties"></property>
	</bean>	
	<bean class="com.mugil.shapes.Circle" id="circleId">
	</bean>	
	<context:annotation-config/>
</beans>

circle.java

public class Circle implements Shape{		
	private Point center;
	
	@Override
	public void drawShape() {
		System.out.println("Shape of Circle ");
		System.out.println("Center of Cirlce "+ getCenter().getX() + " - " + getCenter().getY());
	}

	public Point getCenter() {
		return center;
	}

	@Resource(name="pointC")
	public void setCenter(Point center) {
		this.center = center;
	}
	
	@PostConstruct
	public void initilizeMe() 
	{
		System.out.println("Initialized");
	}
	
	@PreDestroy
	public void destroyMe() 
	{
		System.out.println("Derstroyed");
	}
}

If name is not specified after the @Resource it will look for same name matching bean in the spring.xml file.

@PostConstruct and @PreDestroy will be called when circle bean is initialized and destroyed

Defining Bean using Annotations
spring.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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="com.mugil.shapes"/>
</beans>

circle.java

@Component
public class Circle implements Shape
{	
.
.
}

drawingApp.java

public class DrawingApp {
	public static void main(String[] args)  {
		 AbstractApplicationContext objContext = new ClassPathXmlApplicationContext("spring1.xml");
		 objContext.registerShutdownHook();
		Shape objShape =  (Shape)objContext.getBean("circle");
.
.
}

Using MessageSource
spring.xml

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basenames">
			<list>
				<value>constant</value>
			</list>
		</property>
	</bean>

constant.properties

TestMessage=Mugil

DrawingApp.java

 AbstractApplicationContext objContext = new ClassPathXmlApplicationContext("spring1.xml");
System.out.println(objContext.getMessage("TestMessage", null, "Default Message", null));

Output

 Mugil

Using instance of Message Source in Bean Class
spring.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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basenames">
			<list>
				<value>constant</value>
			</list>
		</property>
	</bean>
	<context:annotation-config/>
	<context:component-scan base-package="com.mugil.shapes"/>
</beans>

circle.java

@Component
public class Circle implements Shape{		
	private Point center;
	
	@Autowired
	private MessageSource messageSource;	
	
	@Override
	public void drawShape() {
		System.out.println("Shape of Circle ");		
		System.out.println(this.messageSource.getMessage("TestMessage", null, "Vannan", null));
	}

	public Point getCenter() {
		return center;
	}

	@Resource(name="pointC")
	public void setCenter(Point center) {
		this.center = center;
	}
	
	public MessageSource getMessageSource() {
		return messageSource;
	}

	public void setMessageSource(MessageSource messageSource) {
		this.messageSource = messageSource;
	}
	
}

this.messageSource.getMessage(“TestMessage”, null, “Vannan”, null)

Variable substitution in Message Source

circle.java

@Component
public class Circle implements Shape{		
	private Point center;
	
	@Autowired
	private MessageSource messageSource;
	
	
	@Override
	public void drawShape() {
		System.out.println("Center of Cirlce");		System.out.println(this.messageSource.getMessage("TestMessage2", new Object[]{center.getX(), center.getY()}, "Vannan", null));
	}
.
.
.
}

this.messageSource.getMessage(“TestMessage2”, new Object[]{center.getX(), center.getY()}, “Vannan”, null)

constant.properties

TestMessage=Mugil
TestMessage2=Center of Circle : ({0}, {1})

@Required
Incase the bean value is not defined using required will display the spring error message instead of null pointer exception for the bean whose value is not defined.

spring.xml

<bean class="com.mugil.shapes.Circle" id="circleId">		
</bean>

Note above the pointA is undefined for above circle bean

Spring Error without @Required annotation

Exception in thread "main" java.lang.NullPointerException
	at com.mugil.shapes.Circle.drawShape(Circle.java:11)
	at com.mugil.shapes.DrawingApp.main(DrawingApp.java:17)

circle.java

public class Circle implements Shape{
	private Point center;
	
	@Override
	public void drawShape() {
		System.out.println("Shape of Circle ");
		System.out.println("Center of Cirlce "+ getCenter().getX() + " - " + getCenter().getY());
	}

	public Point getCenter() {
		return center;
	}

	@Required
	public void setCenter(Point center) {
		this.center = center;
	}		
}

spring.xml

<bean class="com.mugil.shapes.Circle" id="circleId">		
</bean>
	
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>

Spring Error is Thrown

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'circleId' defined in class path resource [spring1.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanInitializationException: Property 'center' is required for bean 'circleId'

Autowired Annotation

  1. @Autowired works by taking into consideration type,name,qualifier
  2. If type not found name will be considered

spring.xml(by Type)

<beans>
	<bean id="PointA" class="com.mugil.shapes.Point">
		<property name="x" value="0"/>
		<property name="y" value="20"/>
	</bean>	
	<bean class="com.mugil.shapes.Circle" id="circleId"></bean>	
	<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
</beans>

spring.xml(by Name)

<beans>
	<bean id="center" class="com.mugil.shapes.Point">
		<property name="x" value="0"/>
		<property name="y" value="20"/>
	</bean>	
	<bean class="com.mugil.shapes.Circle" id="circleId"></bean>	
	<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
</beans>

In above xml center is the name of instance variable in circle class
spring.xml(by Qualifier)

<?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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-2.5.xsd">		
	<bean id="pointA" class="com.mugil.shapes.Point">
		<qualifier value="circle"/>			
		<property name="x" value="20"/>
		<property name="y" value="0"/>
	</bean>	
	<bean class="com.mugil.shapes.Circle" id="circleId"></bean>	
	<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
</beans>

circle.java

public class Circle implements Shape{
	@Autowired
	@Qualifier("circle")
	private Point center;
	
	@Override
	public void drawShape() {
		System.out.println("Shape of Circle ");
		System.out.println("Center of Cirlce "+ getCenter().getX() + " - " + getCenter().getY());
	}

	public Point getCenter() {
		return center;
	}
	
	public void setCenter(Point center) {
		this.center = center;
	}		
}