Spring Annotations @Qualifier or @Resource

What Doesn’t Change

app-context.xml

[sourcecode language=”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”
xmlns:p=”http://www.springframework.org/schema/p”
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:annotation-config/>

<bean id=”profile” class=”com.skills421.spring15.beans.Profile”/>

<bean id=”student1″ class=”com.skills421.spring15.beans.Student”
p:name=”John Doe”
p:age=”21″/>

<bean id=”student2″ class=”com.skills421.spring15.beans.Student”
p:name=”Jane Doe”
p:age=”19″/>

</beans>
[/sourcecode]

Student.java

[sourcecode language=”java”]
package com.skills421.spring15.beans;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class Student
{
private Integer age;
private String name;

@PostConstruct
public void init()
{
System.out.println(“Constructed Student: “+name+” (“+age+”)”);
}

@PreDestroy
public void destroy()
{
System.out.println(“About to Destroy Student: “+name+” (“+age+”)”);
}

public Integer getAge()
{
return age;
}

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

public String getName()
{
return name;
}

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

}
[/sourcecode]

What Changes

Profile – using @Qualifier

[sourcecode language=”java”]
package com.skills421.spring14.beans;

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

public class Profile
{
@Autowired
@Qualifier(“student1”)
private Student student;

public Profile()
{
System.out.println(“Profile()”);
}

public void printName()
{
System.out.println(“Name: “+student.getName());
}

public void printAge()
{
System.out.println(“Age: “+student.getAge());
}
}
[/sourcecode]

Profile – using @Resource

[sourcecode language=”java”]
package com.skills421.spring15.beans;

import javax.annotation.Resource;

public class Profile
{
private Student student;

public Profile()
{
System.out.println(“Profile()”);
}

public Student getStudent()
{
return student;
}

@Resource(name=”student1″)
public void setStudent(Student student)
{
this.student = student;
}

public void printName()
{
System.out.println(“Name: “+student.getName());
}

public void printAge()
{
System.out.println(“Age: “+student.getAge());
}
}
[/sourcecode]

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.