2017-10-04 60 views
2

我的自定義事件春季事件沒有得到公佈

public class TestEvent<E> { 
    private E object; 
} 

測試類

public class Test{ 
    String message; 
} 

類,監聽事件有以下監聽

@Component 
public class TestEventListener{ 
    // This listener works 
    @EventListener 
    public void testEvent(Test test) { 
     logger.info("Test Received"); 
    } 
    // This listener doesn't work 
    @EventListener 
    public void testEvent(TestEvent<Test> testEvent) { 
     logger.info("Received"); 
    } 
} 

代碼發佈事件

@Service 
public class TestService{ 
    @Autowired 
    private ApplicationEventPublisher applicationEventPublisher; 

    public void sendMessage(){ 
     Test test = new Test(); 
     // Event is published 
     applicationEventPublisher.publishEvent(test); 
     TestEvent<Test> testEvent = new TestEvent(test) 
     // Event is not published 
     applicationEventPublisher.publishEvent(testEvent); 
    } 
} 

不知道代碼有什麼問題,但調用永遠不會到達我的監聽器。我正在使用Spring 4.3.3 RELEASE

+0

請給我們一個完整的例子。 –

+0

謝謝@SotiriosDelimanolis,我已經添加了其他信息 – Suchit

+0

您的代碼不應該編譯 - 只有在您嘗試發佈它之後纔會定義'testEvent'。 – chrylis

回答

1

我能解決這個問題。代碼更改如下:

public class TestEvent<E> implements ResolvableTypeProvider { 
    private E object; 

    @Override 
    public ResolvableType getResolvableType() { 
     return ResolvableType.forClassWithGenerics(getClass(), 
       ResolvableType.forInstance(object)); 
     } 
}