lundi 18 mars 2019

How to access private method from Spring service?

I have a service with public methods for database manipulation marked with org.springframework.transaction.annotation.Transactional annotation.

I want to access private method (without Transactional annotation) via Java reflection: service.getClass().getDeclaredMethod('privateMethod', args).

When I call it, I fetch java.lang.NoSuchMethodException. When I delete all the Transactional annotated methods, it works. Is there any reason for such behaviour and how can I solve it?

public class MyService {

    @Transactional(readOnly = true)
    public Integer publicMethodMarkedWithTransactional(int a, int b) {
        //couple of database requests
        return privateMethod(b, a);
    }

    private Integer privateMethod(int a, int b) {
        return a + b;
    }

}

public class MyServiceTest {

    @Autowired
    private MyService service;

    @Test
    public void test() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method privateMethod = service.getClass().getDeclaredMethod("privateMethod", int.class, int.class);
        privateMethod.setAccessible(true);
        int res = (int) privateMethod.invoke(service, 5, 10);
        assertEquals(5 + 10, res);
    }

}





Aucun commentaire:

Enregistrer un commentaire