1 package com.atlassian.activeobjects.spring;
2
3 import org.springframework.beans.factory.FactoryBean;
4
5 import static com.google.common.base.Preconditions.checkNotNull;
6
7 public final class OptionalServiceFactoryBean<T> implements FactoryBean {
8 private final T service;
9 private final T defaultValue;
10 private final Class<T> type;
11
12 public OptionalServiceFactoryBean(Class<T> type, T service, T defaultValue) {
13 this.type = checkNotNull(type);
14 this.service = checkNotNull(service);
15 this.defaultValue = checkNotNull(defaultValue);
16 }
17
18 @Override
19 public Object getObject() throws Exception {
20 try {
21 service.toString();
22 return service;
23 } catch (RuntimeException e) {
24 if (e.getClass().getSimpleName().equals("ServiceUnavailableException")) {
25 return defaultValue;
26 }
27 throw e;
28 }
29 }
30
31 @Override
32 public Class getObjectType() {
33 return type;
34 }
35
36 @Override
37 public boolean isSingleton() {
38 return true;
39 }
40 }