开发者

how to wire a list of beans in spring

What is the best way to wire a list of beans in spring xml, the catch is that each bean's data must be defined in the xml file (this is because during this sprint they will come from xml, next sprint from db, so its not worth it to put too much time into creation).

this is what i have, but there must be a better way:

   <bean id="annouce1" class="com.company.domain.Announcement">
       <property name="body" value="bodyasfsdf"/>
       <property name="title" value="title"/>
       <property name="linkText" value=">>"/>
       <property name="linkUrl" value="http://google.com"/>
   </bean>
   <bean id="annouce2" class="com.company.domain.Announcement">
       <property name="body" value="bodyasfsdf"/>
       <property name="title" value="title"/>
       <property name="linkText" value=">>"/>
       <property name="linkUrl" value="http://google.com"/>
   </bean>
       <bean id="annouce3" class="com.company.domain.Announcement">
       <property name="body" value="bodyasfsdf"/>
       <property name="title" value="title"/>
       <property name="linkText" value=">>"/>
       <property name="linkUrl" value="http://google.com"/>
   </bean>
       <bean id="annouce4" class="com.company.domain.Announcement">
       <property name="body" value="bodyasfsdf"/>
       <property name="title" value="title"/>
       <property name="linkText" value=">>开发者_开发百科;"/>
       <property name="linkUrl" value="http://google.com"/>
   </bean>


   <util:list id="homepageAnnoucements" scope="singleton">
          <ref bean="annouce1"/>
          <ref bean="annouce2"/>
          <ref bean="annouce3"/>
          <ref bean="annouce4"/>
   </util:list>


It came with a great surprise to me, but since Spring 2.5 you can actually write:

@Resource
private List<Announcement> announcements;

And Spring will find all beans of type Announcement and inject them using a list. Of course the old school of fetching the beans manually still applies:

@Resource
private ApplicationContext ctx;

@PostConstruct
public void init() {
    Map<String, Announcement> announcementsBeans = ctx.getBeansOfType(Announcement.class);
    List<Announcement> announcements = announcementsBeans.values();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜