简体   繁体   中英

How to autowire map

I have very simple problem. But I can't find out where I am wrong. I use spring 2.0.2. I want to set property of Map myTasks using Autowire, but as a result I have myTasks = null.

my code: In file spring:

<bean id="Service" class="Service" autowire="byType"/> 
<bean id="FirstTask" class="FirstTask"/>
<bean id="SecondTask" class="SecondTask"/>

where FirstTask, SecondTask extends MyTask

Service.class

class Service{
  private Map<String, MyTask> myTasks;
  public Map<String, MyTask> getMyTasks(){return myTasks;}
  public void MyTasks(Map<String, MyTask> myTasks){this.myTasks = myTasks;}}

As far as I understand, Spring 2.0.2 doesn't support autowiring a map of beans this way. You can use ApplicationContextAware and getBeansOfType() instead:

public class Service implements ApplicationContextAware {
    public void setApplicationContext(ApplicationContext ctx) {
        myTasks = (Map<String, MyTask>) ctx.getBeansOfType(MyTask.class);
    }
    ...
}

How is myTasks declared in the Spring config file ? If you are not sure , you could use use util:map to achieve this

Refer http://static.springsource.org/spring/docs/2.0.2/reference/xsd-config.html#xsd-config-body-schemas-util-map

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