I am working on a simple Spring Core project. As we know to work with Spring Core we need to provide some configuration metadata to the IoC Container and the configuration metadata can be supplied in 3 forms. Source is here
- XML-based configuration
- Java-based configuration
- Annotation-based configuration
Let's consider an example. I have a class Team
.
package com.altafjava.bean;
public class Team {
private String teamName;
private Set<String> players;
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public void setPlayers(Set<String> players) {
this.players = players;
}
}
As we can see it has 2 attributes and we want to inject those values by using Setter Injection
. We can do this by using XML-based configuration
as:
<bean id="team" class="com.altafjava.bean.Team">
<property name="teamName" value="Avengers" />
<property name="players">
<set>
<value>Iron Man</value>
<value>Captain America</value>
<value>Thor</value>
<value>Hulk</value>
<value>Thor</value>
</set>
</property>
</bean>
We can also do this by using Java-based configuration
as:
@Configuration
public class AppConfig {
@Bean
public Team team() {
Team team = new Team();
team.setTeamName("Football Players");
Set<String> players = new HashSet<>();
players.add("Ronaldo");
players.add("Messi");
players.add("Salah");
players.add("Messi");
team.setPlayers(players);
return team;
}
}
Now the question is how can we do this by using Annotation-based configuration
?
In Annotation-based configuration generally, we use stereotype annotation like @Component
, @Service
, @Controller
, @Repository
.