How can I connect to Spring 4.2 ApplicationEventPublisher without using autwire using xml arg constructor?

I see there are many implementations, but how to use the default implementation without using autowire and using xml config?

+3


source to share


1 answer


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

To get ApplicationEventPublisher

, you can implement ApplicationEventPublisherAware

and implement a method, is ApplicationContext

aware of this interface, and will call the setter to give you ApplicationEventPublisher

.

public SomeClass implementens ApplicationEventPublisherAware {
    private ApplicationEventPublisher publisher;

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

      

With annotation, you can just put @Autowired

in the field

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

      

If this is a required dependency I would suggest using constructor injection, an added benefit (IMHO) is that you can create a field final

and that you cannot create 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 an annotated method @Bean

that takes an argument ApplicationEventPublisher

.

@Configuration
public class SomeConfiguration {

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

      

For XML, you will need to autoincrement the constructor, you can specify it on a specific bean.

<bean id="someId" class="SomeClass" autowire="constructor" />

      

+4


source







All Articles