Monday, June 15, 2009

Spring Dependency Injection Questions

This past week, we had our “Beta” run of Intertech’s new Complete Spring Core and Complete Spring Web classes. The latest Spring (2.5.6 with mentions of Spring 3) and Spring MVC/Web Flow are taught in these classes.

I had a great group of students to help give this new class its inaugural flight. While a little on the quiet side, they had wonderful questions and some great insight at the conclusion of our class for how to improve it. I thought I would share two questions that came out this week’s class.

Question #1 (thanks Sharon) - What happens when you use for dependency injecting a property but the property is a List in the actual class? For example, what if the bean definition looked something like this…

And the class looked like this…

public class Player
{
private List teams;
public void setTeams(List teams) {
this.teams = teams;
}
}

The implementation class of the collection bean property does not have to match or property definition in the Spring configuration. Both can be used interchangeably with any type of java.util.Collection. The element wires a collection to the bean and ensures that there are no duplicates. But, as in this case, the underlying collection is still a list. So in this example, the Player bean will have a List of team Strings, but the duplicate “Yankees” will be removed.

Question #2 (thanks Kurt) - Another great question came when we looked at the @Autowire annotation that was added in Spring 2.5. This annotation can be used on any method in the class to conduct dependency injection. The question was what if the @Autowire is used on multiple methods to dependency inject the same property? For example…

public class Player {
private String name;
private Team team;
@Autowired
public void initializePlayer(Team team){
this.team =
team;
}
@Autowired
public void initializePlayerAgain(Team team){
this.team = team;
}
}

In fact, both methods will get called and a Team will get passed to both methods. While this works, we could not think of a good reason for its use.If you have interest in exploring Spring, please contact our office (651-994-8558) and ask for Dan McCabe. I think our Spring training is the most complete (pun absolutely intended!).

1 comment:

  1. Hey Jim, nice to see u blogging, i'm just next door. Spring is nice & gets kudos for forcing J2EE to change but XML and Annotations are still very loose contracts for defining an application's entire object collaboration.

    ReplyDelete