Introduction
Read the first chapter here.
In this, the second chapter we will cover more details about constructor injection in Spring; until now we saw:
- How you are spared from creating objects for your classes and delegate that work to Spring
- How to inject primitive values to the classes using constructor injection
In this chapter, we will see how to pass reference arguments to the classes rather than passing primitive types. In our "Popular Talent Show" we saw a juggler so far. Next, we have another performer who can juggle balls as well as sing, both at the same time, which is a very unique talent, so to showcase that let us write an interface first:
- public interface Song
- {
- void Sing();
- }
Next, we will have a concrete implementation of this type:
- public class Singer implements Song
- {
- private static String[] Lines =
- {
- "I'm never lettin' go",
- "No, no, no, won't let go",
- "When you want it, when you need it",
- "You'll always have the best of me",
- "I can't help it, believe it",
- "You'll always get the best of me",
- "I may not always know what's right",
- "But I know I want you here tonight",
- "Gonna make this moment last for all your life",
- "Oh ya this is love and it really means so much",
- "I can tell from every touch"
- };
- @Override
- public void Sing()
- {
- for (int i = 0; i < Lines.length; i++)
- {
- System.out.println(Lines[i]);
- }
- }
- }
That's cool. So far, we have a favourite song who our singer would be singing, this popular song of Bryan Adams (his favorite singer) on the show along with Juggling, so let's create a class for the SingingJuggler:
- public class SingingJuggler extends Juggler
- {
- private Song _song;
- public SingingJuggler(Song song)
- {
- super();
- _song = song;
- }
- public SingingJuggler(int beanCount, Song song)
- {
- super(beanCount);
- _song = song;
- }
- public void Perform() throws PerformaceException
- {
- super.Perform();
- System.out.println("While singing...");
- _song.Sing();
- }
- }


Join the conversation! Your thoughts help the community grow.