Spring Annotations @Qualifier or @Resource


What Doesn’t Change

app-context.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>

Student.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;
}

}

What Changes

Profile – using @Qualifier

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());
}
}

Profile – using @Resource

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());
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Up ↑

%d bloggers like this: