Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I wire in Spring 4.2 ApplicationEventPublisher with out using autowire using xml constructor arg?

Tags:

spring

events

I see there are lots of implementations, but how do I use the default implementation without using autowire and using xml config?

like image 508
testing123 Avatar asked Oct 26 '25 02:10

testing123


1 Answers

There are several option, you can use annotations, implement and interface or explicitly declare the dependency in xml or java config.

To get the ApplicationEventPublisher you can implement the ApplicationEventPublisherAware and implement the method, the ApplicationContext knows about this interface and will call the setter to give you the ApplicationEventPublisher.

public SomeClass implementens ApplicationEventPublisherAware {
    private ApplicationEventPublisher publisher;

    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher= applicationEventPublisher;
    }
}

With annotation you can just put @Autowired on the field

public SomeClass implementens ApplicationEventPublisherAware {
    @Autowired
    private ApplicationEventPublisher publisher;
}

If it is a required dependency I would suggest using constructor injection, added benefit (IMHO) is that you can make the field final and that you cannot construct an invalid instance.

public SomeClass implementens ApplicationEventPublisherAware {
    private final ApplicationEventPublisher publisher;

    @Autowired
    public SomeClass(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher= applicationEventPublisher;
    }

When using Java Config you can simply create a @Bean annotated method which takes an ApplicationEventPublisher as argument.

@Configuration
public class SomeConfiguration {

    @Bean
    public SomeClass someClass(ApplicationEventPublisher applicationEventPublisher) {
        return new SomeClass(applicationEventPublisher);
    }
}

For XML you would need to autowire the constructor, you can specify this on the specific bean element.

<bean id="someId" class="SomeClass" autowire="constructor" />
like image 99
M. Deinum Avatar answered Oct 27 '25 17:10

M. Deinum