I'm using Spring 4 and was following the Rossen Stoyanchev's blog post about using websockets in Spring. I was able to get everything working but I'm not sure what the best way to use a custom object mapper when sending application/json.
I'm injecting a SimpMessageSendingOperations and calling convertAndSend. I'm not positive but I'm pretty sure I'm getting a SimpMessagingTemplate (it implements SimpMessageSendingOperations) which contains a setMessageConverter. This method takes a MessageConverter and there is a MappingJackson2MessageConverter class but of course it uses it's own internal ObjectMapper which cannot be redefined.
So what it looks like I have to do is create a custom MessageConverter and define my custom ObjectMapper within it so I can pass it to an instance of SimpMessagingTemplate that I can then inject into my classes.
This seems like it would work, but also more involved than I expected. Am I overlooking something?
Looks like it is possible, but will be made easier in Spring 4.0.1
See - https://jira.springsource.org/browse/SPR-11184
Quote from the bug report above.
In the mean time, with #EnableWebSocketMessageBroker setup you can:
remove the annotation
extend WebSocketMessageBrokerConfigurationSupport instead of implementing WebSocketMessageBrokerConfigurer
override brokerMessageConverter() method and remember to keep #Bean in the overriding method
Nowadays you can do it like this:
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
#Override
public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
// Avoid creating many ObjectMappers which have the same configuration.
converter.setObjectMapper(getMyCustomObjectMapper());
messageConverters.add(converter);
// Don't add default converters.
return false;
}
...
}
Unfortunately ObjectMapper cannot be given directly to MappingJackson2MessageConverter's constructor, meaning it will first create a useless ObjectMapper.
Related
I'm trying to implement RFC 7807 in my Spring Boot project using zalando problem-spring-web https://github.com/zalando/problem-spring-web
I've done the setup according to this guide https://github.com/zalando/problem-spring-web/tree/master/problem-spring-web
When an exception is thrown, the Problem instance does get generated, but its serialized JSON form is not as expected, most notably the stack trace is included when it shouldn't.
After some debugging, it seems that the ProblemModule is not registered in the ObjectMapper that is used to serialize the problem (its setupModule method is never called). I was under the impression that declaring a bean of type Module was enough to have it picked up by Spring and registered in the ObjectMapper, but it doesn't happen here.
The doc says
In case you want to enable stack traces, please configure your
ProblemModule as follows:
ObjectMapper mapper = new ObjectMapper()
.registerModule(new ProblemModule().withStackTraces());
which seems to imply that you need to instantiate your own ObjectMapper, but then how to make sure that it's used by the library when deserializing the Problem?
Since I can't get the ObjectMapper to register my Modules I figured I had to do it myself so I came up with this solution that seems to work:
#Configuration
public class ProblemConfiguration implements InitializingBean {
#Autowired
ObjectMapper objectMapper;
#Override
public void afterPropertiesSet() {
objectMapper.registerModules(
new ProblemModule(),
new ConstraintViolationProblemModule()
);
}
}
If someone has an idea why it's not working as expected, I'd be glad to hear it :)
Since Spring boot 1.1.0, the JacksonAutoConfiguration creates an ObjectMapper bean and automatically registers all module found in your registered beans,
so you juste need to create does two beans modules and use de already configured ObjectMapper like this:
/*
* Module for serialization/deserialization of RFC7807 Problem.
*/
#Bean
public ProblemModule problemModule() {
return new ProblemModule();
}
/*
* Module for serialization/deserialization of ConstraintViolationProblem.
*/
#Bean
public ConstraintViolationProblemModule constraintViolationProblemModule() {
return new ConstraintViolationProblemModule();
}
use configured ObjectMapper for ex in service Classe
#Autowired
ObjectMapper jacksonObjectMapper
I'm using a bunch of microservices in my project. These microservices all share one common endpoint that returns an object which has been parsed through XML.
Now I'd love to have some kind of default method defined within the Annotation like this:
#RestController
public #interface ComaModule {
Class<? extends Object> clazz();
#RequestMapping("/descriptor")
default ModuleDescriptor getDescriptor() {
ModuleXmlUnmarshaller moduleXmlUnmarshaller = new ModuleXmlUnmarshaller(clazz());
Optional<ModuleDescriptor> moduleDescriptorOptional = moduleXmlUnmarshaller.findModuleDescriptor();
return moduleDescriptorOptional.orElse(null);
}
}
That does not work since I am not able to have a method definition in my annotation. So the hard stuff is that I want to keep #RequestMapping("/descriptor") for this.
In fact I want some kind of aspect for every RestController I use. I read about AOP for Spring and Proxy but thought I might be able to achieve this with Annotations.
May be you can try adding annotation processor class, where you can write the code which have in your post and achieve what your goal.
I'm using jersey and Guice DI and I want to use Mapstruct interfaces
with #Inject annotation.
So is there some way to force Guice to autowire Mapstruct interface implementations ?
You can configure the implementations of the Mappers to be annotated with JSR 330 annotation by using #Mapper(componentModel = "jsr330"). You can find more information in the reference documentation.
You can then bind the Mapper interface with the implementation class in your modules.
One way to bind them is to use Guice Linked Bindings:
bind(MyDtoMapper.class).to(MyDtoMapperImpl.class)
Another way to bind them is to use Instance Bindings:
bind(MyDtoMapper.class).toInstance(MyDtoMapper.INSTANCE)
Ran into issues with using Guice and the jsr330 componentModel, though I don't recall what they were exactly. My use case was a bit more complex because I needed to pass in another service to a mapper decorator as well. Should work for your simple case as well. Ended up doing provider methods in the Guice Module, like so:
public YourModule extends AbstractModule {
//With Decorator
#Provides
#Singleton
FooMapper providesFooMapper(RequiredService requiredSvc) {
FooMapper mapper = Mappers.getMapper(FooMapper.class);
((FooMapperDecorator) mapper).setRequiredService(requiredSvc);
return mapper;
}
//Simple Mapper with no dependencies
#Provides
#Singleton
BarMapper providesBarMapper() {
return Mappers.getMapper(BarMapper.class);
}
}
Works without a hitch, though I would like for the simple case to be handled by MapStruct cleanly at some point. I'll also note that I only use constructor injection; should work the same for setter injection but YMMV.
Thx #Filip. So yeah #Mapper(componentModel = "jsr330") almost made all work only thing I had to create binding for each mapper that I use directly in my code bind(MyDtoMapper.class).toInstance(MyDtoMapper.INSTANCE) and INSTANCE is declared in MyDtoMapper interface this way: MyDtoMapper INSTANCE = Mappers.getMapper( MyDtoMapper.class );
I writing application using spring-boot-starter-jdbc (v1.3.0).
The problem that I met: Instance of BeanPropertyRowMapper fails as it cannot convert from java.sql.Timestamp to java.time.LocalDateTime.
In order to copy this problem, I implemented
org.springframework.core.convert.converter.Converter for these types.
public class TimeStampToLocalDateTimeConverter implements Converter<Timestamp, LocalDateTime> {
#Override
public LocalDateTime convert(Timestamp s) {
return s.toLocalDateTime();
}
}
My question is: How do I make available TimeStampToLocalDateTimeConverter for BeanPropertyRowMapper.
More general question, how do I register my converters, in order to make them available system wide?
The following code bring us to NullPointerException on initialization stage:
private Set<Converter> getConverters() {
Set<Converter> converters = new HashSet<Converter>();
converters.add(new TimeStampToLocalDateTimeConverter());
converters.add(new LocalDateTimeToTimestampConverter());
return converters;
}
#Bean(name="conversionService")
public ConversionService getConversionService() {
ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean();
bean.setConverters(getConverters());
bean.afterPropertiesSet();
return bean.getObject();
}
Thank you.
All custom conversion service has to be registered with the FormatterRegistry. Try creating a new configuration and register the conversion service by implementing the WebMvcConfigurer
#Configuration
public class WebConfig implements WebMvcConfigurer {
#Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new TimeStampToLocalDateTimeConverter());
}
}
Hope this works.
I'll copy my answer from https://stackoverflow.com/a/72781591/140707 since I think the two questions are similar (so the answer applies to both).
Existing answers didn't work for me:
Customizing via WebMvcConfigurerAdapter.addFormatters (or simply annotating the converter with #Component) only works in the WebMvc context and I want my custom converter to be available everywhere, including #Value injections on any bean.
Defining a ConversionService bean (via ConversionServiceFactoryBean #Bean or #Component) causes Spring Boot to replace the default ApplicationConversionService on the SpringApplication bean factory with the custom bean you've defined, which will probably be based on DefaultConversionService (in AbstractApplicationContext.finishBeanFactoryInitialization). The problem is that Spring Boot adds some handy converters such as StringToDurationConverter to the standard set in DefaultConversionService, so by replacing it you lose those conversions. This may not be an issue for you if you don't use them, but it means that solution won't work for everyone.
I created the following #Configuration class which did the trick for me. It basically adds custom converters to the ConversionService instance used by Environment (which is then passed on to BeanFactory). This maintains as much backwards compatibility as possible while still adding your custom converter into the conversion services in use.
#Configuration
public class ConversionServiceConfiguration {
#Autowired
private ConfigurableEnvironment environment;
#PostConstruct
public void addCustomConverters() {
ConfigurableConversionService conversionService = environment.getConversionService();
conversionService.addConverter(new MyCustomConverter());
}
}
Obviously you can autowire a list of custom converters into this configuration class and loop over them to add them to the conversion service instead of the hard-coded way of doing it above, if you want the process to be more automatic.
To make sure this configuration class gets run before any beans are instantiated that might require the converter to have been added to the ConversionService, add it as a primary source in your spring application's run() call:
#SpringBootApplication
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(new Class<?>[] { MySpringBootApplication.class, ConversionServiceConfiguration.class }, args);
}
}
If you don't do this, it might work, or not, depending on the order in which your classes end up in the Spring Boot JAR, which determines the order in which they are scanned. (I found this out the hard way: it worked when compiling locally with an Oracle JDK, but not on our CI server which was using a Azul Zulu JDK.)
Note that for this to work in #WebMvcTests, I had to also combine this configuration class along with my Spring Boot application class into a #ContextConfiguration:
#WebMvcTest(controllers = MyController.class)
#ContextConfiguration(classes = { MySpringBootApplication.class, ConversionServiceConfiguration.class })
#TestPropertySource(properties = { /* ... properties to inject into beans, possibly using your custom converter ... */ })
class MyControllerTest {
// ...
}
I suggest to use #Autowired and the related dependency injection mechanism of spring to use a single ConversionService instance throughout your application. The ConversionService will be instantiated within the configuration.
All Converters to be available application wide receive an annotation (e.g. #AutoRegistered). On application start a #Component FormatterRegistrar (Type name itself is a bit misleading, yes it is "...Registrar" as it does the registering. And #Component as it is fully spring managed and requires dependency injection) will receive #AutoRegistered List of all annotated Converters.
See this thread for concrete implementation details. We use this mechanism within our project and it works out like a charm.
org.springframework.web.servlet.config.annotation.WebMvcConfigurer or any on its implementation is one stop place for any kind of customization in spring boot project. It prvoides various methods, for your Converter requirement.
Just create a new Converter by extending org.springframework.core.convert.converter.Converter<S, T>. Then register it with Spring by your class overriding method org.springframework.web.servlet.config.annotation.WebMvcConfigurer.addFormatters(FormatterRegistry)
Note there are Other types of Converter also which basically starts from ConditionalConverter.
Trying adding
#Converter(autoApply = true)
Its needs to be placed over the convertor class. This works for me in case of Convertor needed for Localdate for interacting to DB.
#Converter(autoApply = true)
public class LocalDateAttributeConverter implements AttributeConverter<LocalDate, Date> {
#Override
public Date convertToDatabaseColumn(LocalDate locDate) {
return (locDate == null ? null : Date.valueOf(locDate));
}
#Override
public LocalDate convertToEntityAttribute(Date sqlDate) {
return (sqlDate == null ? null : sqlDate.toLocalDate());
}
}
This is now applied automatically while interacting with DB.
I'm converting my guice application to a spring based on because of issues I found with the #transaction annotation. When doing so, I came to a issue with the configuration of a custom objectmapper with spring/resteasy. I want to register the hibernate4Module (fasterxml jackson) and a custom deserializer.
I have found many solution when using spring mvc, but I'm not using spring mvc.
I'm looking at the resteasyboostrap class, since there you have control over you factory, but I don't know how to register my new SimpleModule there.
Anyone with any experience? When I'm searching the internet, it seems nobody is trying to do the same thing. Perhaps I'm looking in the wrong places?
This one was eventually an easy one to fix.
Remove the resteasy-jackson provider and write a custom class that you annotate with the spring #Component annotation. Jax-RS picks up the provider and uses the object mapper in the provider.
I was searching in the implementation, but the answer was in the jax-rs api.
#Component
#Provider
#Consumes({"application/*+json", "text/json"})
#Produces({"application/*+json", "text/json"})
public class JacksonProvider extends JacksonJsonProvider {
public JacksonProvider() {
setMapper(new CustomObjectMapper());
}
}