close

  在前一篇Spring3對JSR-330的支援,可以使用@Qualifier指定bean name,以區分同一Interface的不同implementation。而Spring還提供getBeansOfType這個method取所有實作同一Interface的所有的bean:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class,
        value = "com.foo.dao.DaoConfig")
public class TestGetBeansOfType {
    private static Logger logger = LoggerFactory.getLogger(TestGetBeansOfType.class);
    @Autowired
    private ApplicationContext ac;

    @Test
    public void testDao() {
        Map<String, IBaseDao> map = ac.getBeansOfType(IBaseDao.class);
        for (String key : map.keySet()) {
            logger.debug(key);
        }
    }
}

  如何直接操作SpringJUnit4ClassRunner的ApplicationContext,今天方知可以使用@Autowired。藉由getBenasOfType,以下片段@Configuration都成為Return map的入幕之賓:

@Configuration
@Import(RootConfig.class)
public class DaoConfig {  // package com.foo.dao
    private static Logger logger = LoggerFactory.getLogger(DaoConfig.class);
    @Bean(name="accountDao")
    public IBaseDao<Accounts> AccountDao() {
        logger.debug("AccountDao is called!!");
        return new AccountDaoImpl();
    }

    @Bean(name="functionDao")
    public IBaseDao<Functions> FunctionDao() {
        logger.debug("FunctionDao is called!!");
        return new FunctionDaoImpl();
    }
}

arrow
arrow
    全站熱搜

    Jemmy 發表在 痞客邦 留言(0) 人氣()