简体   繁体   中英

Mapping one key to multiple values with @Component

I would like to go from an old util:map XML annotation from a component-oriented map. I am stumbling upon this issue. I already managed to change a first one, with this type of configuration:

Mapped bean:

@Autowired
private Map<String, MyType>    typeMap;

And for each Bean:

@Component("firstType")
public FirstType implements MyType    {}

Then simply calling:

typeMap.get("firstType");

works like a charm. However, here's how this other map is implemented:

<util:map id="routingMap">
    <entry key="one" value-ref="firstReference" />
    <entry key="two" value-ref="firstReference" />
    <entry key="three" value-ref="firstReference" />
    <entry key="four" value-ref="secondReference" />
    <entry key="five" value-ref="secondReference" />
    <entry key="six" value-ref="secondReference" />
    <entry key="seven" value-ref="thirdReference" />
    <entry key="eight" value-ref="secondReference" />
    <entry key="nine" value-ref="secondReference" />
</util:map>

As you can see, there are multiple keys that refer to firstReference and secondReference . Is there a way to simulate this with an annotation like:

@Component(values = "one", "two", "three")

and achieve a similar result ? Or is there no way to do this with Spring annotations ?

This is not possible using @Component , There is an open ticket for this https://jira.spring.io/browse/SPR-6736 .

However you can achieve this using @Bean
Remove @Component from your implementation classes.

public FirstType implements MyType    {}

Create a config class like this

@Configuration
Class Config {

   @Bean(name = "one", "two", "three")
   public FirstType myFirstTypeMethod() {
      return new FirstType();
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM