Java inject external service

0

I am using this project in the pom of my application:

<dependency>
    <groupId>com.girotan.notification</groupId>
    <artifactId>notification-service-rest-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

Within a service I use an @Service class of the mentioned project NotificationRestClient , like this:

void sendEmailNotificationMessage(ApiEmailNotification apiEmailNotification) throws BusinessException {

    NotificationEnvelope notificationEnvelope = new NotificationEnvelope();
    notificationEnvelope.setType(ApiNotificationType.EMAIL);
    notificationEnvelope.setNotification(apiEmailNotification);

    NotificationRestClient restClient = new NotificationRestClient();
    restClient.send(notificationEnvelope);
}

However this seems inelegant to me, I am using spring. Is there a way to inject NotificationRestClient restClient and not instantiate it as an object?

    
asked by AndreFontaine 26.04.2017 в 23:29
source

1 answer

2

Define a new bean in your configuration class:

@Configuration
public class PompousConfig {

    @Bean
    @Scope("prototype")
    public NotificationRestClient getNotificationRestClient() {
        return new NotificationRestClient();
    }

}

E inject it as follows:

@Autowired
private NotificationRestClient restClient;

void sendEmailNotificationMessage(ApiEmailNotification apiEmailNotification) 
        throws BusinessException {

    NotificationEnvelope notificationEnvelope = new NotificationEnvelope();
    notificationEnvelope.setType(ApiNotificationType.EMAIL);
    notificationEnvelope.setNotification(apiEmailNotification);

    restClient.send(notificationEnvelope);
}

NOTE: You can change the scope of your bean if NotificationRestClient is thread-safe . sub>

    
answered by 27.04.2017 / 01:26
source