json serializer with spring boot - spring-boot

I have BigDecimalSerializer
public class BigDecimalSerializer extends JsonSerializer<BigDecimal> {
#Override
public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers)
throws IOException {
gen.writeString(value.setScale(6, BigDecimal.ROUND_HALF_UP).toString());
}
}
and then
#JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal foo;
is there any way that instead of doing annotate in each member variable, I tell the spring boot at once that apply to all project ?

Try configuring the ObjectMapper by adding a custom module. In case you're using spring-data-rest this can look like this:
#Configuration
public static class ObjectMapperConfigurer extends RepositoryRestConfigurerAdapter {
#Override
public void configureJacksonObjectMapper(final ObjectMapper objectMapper) {
SimpleModule myModule = new SimpleModule();
myModule.addSerializer(BigDecimal.class, BigDecimalSerializer.class);
objectMapper.registerModule(myModule));
}
}
Otherwise simply provide your own ObjectMapper bean and configure it on creation.

Related

How to access properties in BeanFactoryPostProcessor with spring boot 1.5.x

I am trying to get properties from application.yml in BeanFactoryPostProcessor with spring boot 1.5.x:
The application.yml:
prong:
nfcloan:
jackson:
json-sub-types-package:
- com.shuweicloud.starter.acc.dto.request
#ConfigurationProperties(prefix = "prong.nfcloan.jackson")
public class JacksonProperties {
private List<String> jsonSubTypesPackage;
public List<String> getJsonSubTypesPackage() {
return jsonSubTypesPackage;
}
public void setJsonSubTypesPackage(List<String> jsonSubTypesPackage) {
this.jsonSubTypesPackage = jsonSubTypesPackage;
}
}
#Component
public class AccBeanFactoryPostProcessor implements BeanFactoryPostProcessor{
#Autowired
private JacksonProperties jacksonProperties;
#Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
List<String> packages = jacksonProperties.getJsonSubTypesPackage();
// do something
}
}
The main class:
#SpringBootApplication
#EnableConfigurationProperties({JacksonProperties.class})
public class AccountingApplication {
public static void main(String[] args) {
SpringApplication.run(AccountingApplication.class, args);
}
}
But the packages variable is null. How to solve it?
I found a solution:
#Component
public class AccBeanFactoryPostProcessor implements BeanFactoryPostProcessor, EnvironmentAware {
private Environment environment;
#Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
#SuppressWarnings("unchecked")
#Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
List<String> packages = environment.getProperty("prong.nfcloan.jackson.json-sub-types-package", List.class);
// do something
}
}
Spring boot internally uses Binder APIs to "map" the resolved properties into the #ConfigurationProperties beans.
Indeed, this resolution happens during the spring boot startup process after the BeanFactoryPostProcessors get created.
Now your solution will clearly work, because you kind of "bypass" this resolution.
However if you want to still have the Configuration as an instance of JacksonProperties (might be relevant if you have a lot of properties to resolve, or in general prefer to work more in a more spring-ish manner), you can use this binder API:
// inside the "postProcessBeanFactory" method, using the injected environment
BindResult<ExampleProperties> bindResult = Binder.get(environment)
.bind("prong.nfcloan.jackson", JacksonProperties.class);
JacksonProperties properties = bindResult.get();

Injecting Spring Dependencies into ConstrantValidator

I'm using Bean Validation. I have a custom validator #MyValidator that needs to look up a value with an injected Spring managed DAO object. How can I get access to this? Spring isn't injecting the DAO into my "MyValidator" object.
#Component
public class CodeListValidator implements ConstraintValidator<CodeList, String> {
#Autowired
private ICodeListCommonService codeListCommonService;
private CodeListEnum codeListID;
#Override
public void initialize(CodeList constraintAnnotation) {
this.codeListID = constraintAnnotation.value();
}
#Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return codeListCommonService.doesCodeEntityExistForCodeList(codeListID.getDbCodeListId(), value, ProviderConstants.CODE_LIST_STATUS_ACTIVE);
}
}
The "codeListCommonService" is null. This is because Spring isn't creating the class - but how can I get this to work with Spring AoP?
The use of this validator looks like this:
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
MyObject validateMe = new MyObject();
Set<ConstraintViolation<MyObject>> constraintViolations = validator.validate(validateMe);
For MyObject:
public class MyObject {
#Size(max = 1)
#CodeList(CodeListEnum.CARTYPE)
public String carType;
}
So when the validator runs, it processes the annotations... I just need to get a service injected into the CodeListValidator I made to it can do a DB lookup to verify the value against the DB list of "valid car type values".
EDIT: The solution:
Played around with the idea of making a Spring aware factory- too much integration with existing code.
The solution that seems the best (and it works here) is to make a Spring service that stores the ApplicationContext in a static method so "non-Spring managed" beans can get to them.
So a new service:
#Service
public class SpringApplicationContextService implements ISpringApplicationContextService, ApplicationContextAware {
private static ApplicationContext applicationContext;
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
}
And then any validator or non-Spring bean can get at the Spring beans via:
public class CodeListValidator implements ConstraintValidator<CodeList, String> {
#Autowired
private ICodeListCommonService codeListCommonService;
private CodeListEnum codeListID;
#Override
public void initialize(CodeList constraintAnnotation) {
this.codeListID = constraintAnnotation.value();
}
#Override
public boolean isValid(String value, ConstraintValidatorContext context) {
ICodeListCommonService codeListCommonService = SpringApplicationContextService.getApplicationContext().getBean(ICodeListCommonService.class);
return codeListCommonService.doesCodeEntityExistForCodeList(codeListID.getDbCodeListId(), value, ProviderConstants.CODE_LIST_STATUS_ACTIVE);
}
}
And, of course, the reason for all of this (which is used dozens of times in this app):
#CodeList(CodeListEnum.EMAIL_OPT_OUT_FLAG)
public String emailOptOutFlag;
#CodeList(CodeListEnum.CLEARING_HOUSE)
public String clearingHouse;
The minimum setup for #Autowired to work properly in ConstraintValidator implementation is to have this bean in a Spring #Configuration:
#Bean
public Validator defaultValidator() {
return new LocalValidatorFactoryBean();
}
This allows any beans, including ApplicationContext, to be injected directly into a ConstraintValidator:
#Constraint(validatedBy = DemoValidator.class)
public #interface DemoAnnotation {
// ...
Class<?> beanClass();
}
public class DemoValidator implements ConstraintValidator<DemoAnnotation, String> {
private final ApplicationContext applicationContext;
private Object bean;
#Autowired
public DemoValidator(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
#Override
public void initialize(DemoAnnotation constraint) {
Class<?> beanClass = constraint.beanClass();
bean = applicationContext.getBean(beanClass);
}
#Override
public boolean isValid(String obj, ConstraintValidatorContext context) {
return !obj.isEmpty();
}
}
Demo
For a really flexible validation solution I would recommend Jakub Jirutka's Bean Validator utilizing Spring Expression Language (SpEL) which allows things like:
public class Sample {
#SpELAssert("#myService.calculate(#this) > 42")
private int value;
}

#Autowired does not work with #Configurable

I am trying to do an image upload API. I have a ImageUpload task as follows,
#Component
#Configurable(preConstruction = true)
#Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class ImageUploadTask implements Callable<JSONObject> {
#Autowired
private ImageUploadService imageUploadService;
#Override
public JSONObject call() throws Exception {
....
//Upload image via `imageUploadService`
imageUploadService.getService().path('...').post('...'); // Getting null pointer here for imageUploadService which is a WebTarget
}
}
The ImageUploadService looks like the below,
#Component
public class ImageUploadService {
#Inject
#EndPoint(name="imageservice") //Custom annotation, battle tested and works well for all other services
private WebTarget imageservice;
public WebTarget getService() {
return imageservice;
}
}
Here is the spring boot application class,
#ComponentScan
#EnableSpringConfigured
#EnableLoadTimeWeaving(aspectjWeaving=EnableLoadTimeWeaving.AspectJWeaving.ENABLED)
#EnableAutoConfiguration
public class ImageApplication extends SpringBootServletInitializer {
#Bean
public InstrumentationLoadTimeWeaver loadTimeWeaver() throws Throwable {
InstrumentationLoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();
return loadTimeWeaver;
}
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.addListener(new RequestContextListener());
}
public static void main(String[] args) throws IOException {
SpringApplication.run(ImageApplication.class);
}
}
Additional information :
Spring version of dependencies are at 4.2.5.RELEASE
pom.xml has dependencies added for spring-aspects and
spring-instrument
I am getting a NullPointerException in ImageUploadTask. My suspicion is that #Autowired doesn't work as expected.
Why wouldn't work and how do I fix this?
Is it mandatory to use #Autowired only when I use #Conigurable, why not use #Inject? (though I tried it and getting same NPE)
By default the autowiring for the #Configurable is off i.e. Autowire.NO beacuse of which the imageUploadService is null
Thus update the code to explicity enable it either as BY_NAME or BY_TYPE as below.
#Component
#Configurable(preConstruction = true, autowire = Autowire.BY_NAME)
#Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class ImageUploadTask implements Callable<JSONObject> { .... }
Rest of the configuration viz. enabling load time weaving seems fine.
Also regarding #Inject annotation have a look here which pretty much explains the difference (or similarity perhaps)

How can I access Spring ConfigurationProperties inside a custom JsonDeserializer?

I have a custom Json Deserializer that I am trying to Autowire ConfigurationProperties into. However, the property is always null. I tried using the SpringBeanAutowiringSupport but for some reason the CurrentWebApplicationContext is null.
How can I get the #Autowired to work in my custom deserializer?
Update:
I am using #JsonDeserialize(using = Deserializer.class) on my domain class, which is be utilized through a RestTemplate call in a service class.
I am using Spring Boot 1.4.
HealthDeserializer
public class HealthDeserializer extends JsonDeserializer<Health> {
#Autowired
private HealthMappings mappings;
#Override
public Health deserialize(JsonParser jp, DeserializationContext ctx) throws IOException, JsonProcessingException {
mappings.lookup(...);
}
}
HealthMappings
#Component
#ConfigurationProperties(prefix="health_mapping")
public class HealthMappings {
...
}

Rest Custom HTTP Message Converter Spring Boot 1.2.3

I want to create a custom of HttpMessageConverter using Rest, Json, Spring Boot 1.2.3 and Spring 4, However my custom HTTPMessageConverter its' never called.
I have preformed the following steps :
1: Created a class that extends AbstractHttpMessageConverter
#Component
public class ProductConverter extends AbstractHttpMessageConverter<Employee> {
public ProductConverter() {
super(new MediaType("application", "json", Charset.forName("UTF-8")));
System.out.println("Created ");
}
#Override
protected boolean supports(Class<?> clazz) {
return false;
}
#Override
protected Employee readInternal(Class<? extends Employee> clazz,
HttpInputMessage inputMessage) throws IOException,
HttpMessageNotReadableException {
InputStream inputStream = inputMessage.getBody();
System.out.println("Test******");
return null;
}
#Override
protected void writeInternal(Employee t,
HttpOutputMessage outputMessage) throws IOException,
HttpMessageNotWritableException {
// TODO Auto-generated method stu
}
}
2: I create a configuration class to register HTTPMessageConverters
#Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter{
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
System.out.println("Configure Message Converters");
converters.add(new ProductConverter());
super.configureMessageConverters(converters);
//super.extendMessageConverters(converters);
}
}
3: The rest class method
#RequestMapping(value="/{categoryId}" ,method=RequestMethod.POST, consumes="application/json")
#PreAuthorize("permitAll")
public ResponseEntity<ProductEntity> saveProduct(#RequestBody Employee employee , #PathVariable Long categoryId) {
logger.log(Level.INFO, "Category Id: {0}" , categoryId);
ResponseEntity<ProductEntity> responseEntity =
new ResponseEntity<ProductEntity>(HttpStatus.OK);
return responseEntity;
}
My Custom HTTPMessageCoverter it's created but is never called ? Is there a configuration or step I'm missing ? any input or advice is appreciated.
After overriding the (AbstractHttpMessageConverter) class methods, I found out there's two annotations for achieving polymorphism #JsonTypeInfo and #JsonSubTypes. For anyone who wants achieve polymorphism can use these two annotations.
I believe you want to configure these message converters using the configureMessageConverters method in a configuration class that extends WebMvcConfigurerAdapter. I've done this myself with a converter for CSV content. I've included that code below. This link shows an example as well. This link may also be helpful. It seems like with Spring configuration it is not always clear on the best place to configure things. :) Let me know if this helps.
#Configuration
public class ApplicationWebConfiguration extends WebMvcConfigurerAdapter {
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
converters.add(new CsvMessageConverter());
}
}
You will also need top modify your supports() method to return true for classes supported by the converter. See the Spring doc for AbstractHttpMessageConverter supports method.

Resources