Altaf Ansari
Altaf Ansari

Reputation: 776

How to inject Set<String> with Annotation-based configuration in Setter Injection?

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

  1. XML-based configuration
  2. Java-based configuration
  3. 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.

Upvotes: 0

Views: 194

Answers (2)

Vincent Rivoire
Vincent Rivoire

Reputation: 21

Not possible as annotations are used at compile time and since reflection is not compiled...

Upvotes: 0

josejuan
josejuan

Reputation: 9566

Is not possible since an annotation cannot contains any type value.

Upvotes: 0

Related Questions