Warning. I understand that this may be an abuse of intent regarding the default beans beans and / or Java 8 interface methods. I am looking for concrete and reasoned criticism of why this might be an unsafe approach that I do not recognize.
I defined a class that gives me static access to the context of a running application:
@Component
public class BeanAccessor implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static <T> T getSingleton(Class<T> clazz){
return applicationContext.getBean(clazz);
}
public static <T> T getSingleton(String beanName, Class<T> clazz){
return applicationContext.getBean(beanName, clazz);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
BeanAccessor.applicationContext = applicationContext;
}
}
Then I can use these BeanAccessor methods inside the default interface methods to access spring managed beans inside the method.
, , , ( , , 'this'). "" , , .
, , https://kerflyn.wordpress.com/2012/07/09/java-8-now-you-have-mixins/, , .
:
public interface ClientAware {
String TENANT_NAME = "TENANT_NAME";
default ClientDetails clientDetails() {
ClientDetailsService service = BeanAccessor.getSingleton(ClientDetailsService.class);
return service.loadClientByClientId(SecurityUtil.getClientId());
}
default Map<String, Object> clientInfo() {
return clientDetails().getAdditionalInformation();
}
default String tenant() {
return (String) clientInfo().get(TENANT_NAME);
}
}
( , ):
@RestController
@RequestMapping("/documents")
public class Documents implements WrapAware, ClientAware {
@Autowired
private DocumentService docService;
@RequestMapping(method = RequestMethod.GET)
public Object byPathAndTenant(@RequestParam("path") String path) {
return ok(docService.getDocumentsByPathAndTenant(path, tenant()));
}
}
, beans , , . , .