2

奇怪的主题继续问题本身:) 有没有办法从弹簧应用程序上下文中到达弹簧测试类?问题详细信息作为注释块隐藏在“SimpleDaoHandler”类中:)

测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/applicationContext-core.xml")
public class DbFuntionTests {

    @TestAnnotation
    private UserSessionDao userSessionDao; 

    @Test
    public void testOracleTimestamp() throws Exception {
        userSessionDao.findAll();
    }
}

spring上下文初始化后的一个handler类:

@Component
public class SimpleDaoHandler implements ApplicationContextAware, InitializingBean {
    private ApplicationContext applicationContext;
    private static Logger logger = Logger.getLogger(SimpleDaoHandler.class);

    @Override
    public void afterPropertiesSet() throws Exception {
        //I have the application context now, via method "setApplicationContext"
        // and need to get test class object to get the
        // annotated field "TestAnnotation" because I also need to set this
        // field with my business logic, using reflection.
        // Problem is; test class object is not included in the
        // "applicationContext" as a bean and I don't know how to access my 
        //test class which is already starting the spring context initialization. 
        //I need to get that test class object.
    }

    @Override
    public void setApplicationContext(final ApplicationContext applicationContext)
            throws BeansException {
        this.applicationContext = applicationContext;
    }

有什么线索吗?

4

2 回答 2

2

也许创建一些您的@TestAnnotation? 您可以查看 SpringAutowiredAnnotationBeanPostProcessor扫描具有注释的字段/方法@Autowire并处理它们的 bean。我认为这是您尝试实现的目标,而 bean 后处理器是此类问题的最干净的解决方案(由 Spring 本身使用)。

请看下面的示例 - 对应用程序上下文中每个 bean 的MyAnnotationPostProcessor扫描MyAnnotation并记录适用的字段。(当然,您可以采取一些措施来代替记录;))。请注意您的注释必须已RetentionPolicy.RUNTIME声明;否则,它将在运行时不可见。

public final class MyAnnotationPostProcessor implements BeanPostProcessor {

    private static final Log LOG = LogFactory.getLog(MyAnnotationPostProcessor.class);

    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        final Set<Field> annotatedFields = getAnnotatedFields(bean.getClass());
        for (Field annotatedField : annotatedFields) {
            LOG.info("Post process before initialization " + beanName + "," + annotatedField);
        }
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        final Set<Field> annotatedFields = getAnnotatedFields(bean.getClass());
        for (Field annotatedField : annotatedFields) {
            LOG.info("Post process after initialization " + beanName + "," + annotatedField);
        }
        return bean;
    }

    private Set<Field> getAnnotatedFields(final Class<?> clazz) {
        final Set<Field> annotatedFields = new HashSet<Field>();
        for (Field field : clazz.getDeclaredFields()) {
            if(hasMyAnnotation(field)) {
                annotatedFields.add(field);
            }
        }
        return annotatedFields;
    }

    private boolean hasMyAnnotation(final AccessibleObject ao) {
        return AnnotationUtils.getAnnotation(ao, MyAnnotation.class) != null;
    }
}

测试类和注解:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class MySpringTest {

    @MyAnnotation
    private UserSessionDAO dao;

    @Configuration
    static class TestContext {
        @Bean
        public static MyAnnotationPostProcessor myAnnotationPostProcessor() {
            return new MyAnnotationPostProcessor();
        }
    }

    @Test
    public void test() {

    }
}

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

}
于 2013-05-22T15:18:19.907 回答
0

感谢 Piotrek De,我终于找到了答案。您的注释处理程序类还必须实现 BeanPostProcessor 类。这样,您也可以获得测试应用程序上下文使用的两种方法:

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    try {
        injectGDao(bean);
    } catch (Exception e) {
        throw new BeanInstantiationException(bean.getClass(), e.getMessage(), e.getCause());
    }
    return bean;
}

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    try {
        injectGDao(bean);
    } catch (Exception e) {
        throw new BeanInstantiationException(bean.getClass(), e.getMessage(), e.getCause());
    }
    return bean;
}

每当测试上下文侦听器到达此方法时,您现在就可以到达测试类对象。如前所述,可以在 Piotrek De 的回答中找到更详细的答案。

于 2013-05-28T13:44:05.237 回答