Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

java - How to correct inject map of bean in spring context

I am using component-scan in my spring application. So in spring context I created map:

<util:map id="mapByName" map-class="java.util.concurrent.ConcurrentHashMap">
    <entry key="Name1" value-ref="MyCustomClassName1" />
</util:map>

and in my class annotated by @Service I want to inject this property:

@Inject
private Map<String, MyCustomClassName1> mapByName;

this is still working. Problem just in name of key. When I print this property I got [MyCustomClassName1=org.my.package.service.MyCustomClassName1@cb52f2]

so as you can see name of key is changed from Name1->MyCustomClassName1 (Name of this class). So my question is how to define custom key name in map property ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I were you, I would use Java Config to create a Map, since Java is the best way to create a Java object :) :). Your configuration code would look like this:

@Bean(name = "mapBean")
public Map<String, MyCustomClassName1> mapBean() {
    Map<String, MyCustomClassName1> map = new HashMap<>();
    //populate the map here - you will need to @Autowire the references if they are not defined in this configuration
    return map;
}

And then I would inject it into wherever it's needed like so:

@Resource(name="mapBean")
private Map<String, MyCustomClassName1> map;

Note the use of @Resource instead of @Autowired or @Inject


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...