logo
down
shadow

How to use Spring Converter for some controllers only?


How to use Spring Converter for some controllers only?

Content Index :

How to use Spring Converter for some controllers only?
Tag : java , By : Nick Pegg
Date : January 12 2021, 09:11 PM

Hope that helps Normally speaking, a registered Converter is bound to an input source and an output destination. In your case . The default Spring converter you used will apply the conversion on each matching source-destination pair.
To gain more control over when to apply the conversion, a ConditionalGenericConverter can be used. The interface contains 3 methods:
// RequiresConversion is a custom annotation solely used in this example
// to annotate an attribute as "convertable"
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequiresConversion {
}
@Component
public class SomeConverter implements ConditionalGenericConverter {

    @Override
    public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
        // Verify whether the annotation is present
        return targetType.getAnnotation(RequiresConversion.class) != null;
    }

    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        return Collections.singleton(new ConvertiblePair(String.class, Long.class));
    }

    @Override
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        // Conversion logic here
        // In this example it strips "value" from the source string
        String sourceValue = ((String) source).replace("value", "");
        return Long.valueOf(sourceValue);
    }
}
@RestController
public class SomeController {

    // The path variable used will be converted, resulting in the "value"-prefix 
    // being stripped in SomeConverter
    // Notice the custom '@RequiresConversion' annotation
    @GetMapping(value = "/test/{myvalue}")
    public ResponseEntity myvalue(@RequiresConversion @PathVariable Long myvalue) {
        return new ResponseEntity<>(HttpStatus.OK);
    }

    // As the @RequiresConversion annotation is not present,
    // the conversion is not applied to the @PathVariable
    @GetMapping(value = "/test2/{myvalue}")
    public ResponseEntity myvalue2(@PathVariable Long myvalue) {
        return new ResponseEntity<>(HttpStatus.OK);
    }
}


Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Spring Webflow binding: Converter - java.lang.IllegalArgumentException: Each converter object must implement one of the


Tag : java , By : afds
Date : March 29 2020, 07:55 AM
This might help you Are you sure you should be using the org.springframework.context.support.ConversionServiceFactoryBean? This is a spring-core defined class. It expects the following:
org.springframework.core.convert.converter.GenericConverter
org.springframework.core.convert.converter.Converter
org.springframework.core.convert.converter.ConverterFactory
org.springframework.binding.convert.converters.Converter
@Service("conversionService")
public class MyConversionService extends DefaultConversionService {

    public void ConversionService() {
        addDefaultConverters();
    }

    @Override
    protected void addDefaultConverters() {
        super.addDefaultConverters();
    }

}

Spring MVC and AOP: @Pointcuts only apply for Rest Controllers and not for common Web Controllers


Tag : spring-mvc , By : Edo
Date : March 29 2020, 07:55 AM
it fixes the issue Seems that the problem is in you pointcut definition. You may notice that your advice method is performed only for methods with one parameter, so this is due to the fact that you have specified args(id) in the pointcut declaration. It must work as you expect if you remove args(id), but in this case some workaround must be used to expose parameter value.
I think that this is strange behavior form AspectJ because constructions like execution(* *.*(String, ..)) && args(arg) && target(t)) has clear semantic sense to capture all the methods with String first parameter and expose it to args. It can be a bug or feature, at least, to AspectJ developers.
@Pointcut(value=
"execution(* com.manuel.jordan.controller.*.*Controller.deleteOne(..)) && target(object)")
public void deleteOnePointcut(Object object){}

@Before(value="ControllerPointcut.deleteOnePointcut(object)")
public void beforeAdviceDeleteOne(JoinPoint jp, Object object){
    Object id = jp.getArgs()[0];
    logger.info("beforeAdviceDeleteOne - @Controller: {} - Method: deleteOne - id: {}", object.getClass().getSimpleName(), id);
}

spring MVC org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of ty


Tag : java , By : Tom D
Date : March 29 2020, 07:55 AM
I wish did fix the issue. This is the output I get in my Browser for a Spring MVC using REST , In your dispatcher servlet config xml file make sure you have this:
<mvc:annotation-driven>
     <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
   </mvc:message-converters>
</mvc:annotation-driven>

Complex Spring Converter with Converter inside?


Tag : spring , By : BinaryBoy
Date : March 29 2020, 07:55 AM

spring data mongodb: access default POJO converter from within custom converter


Tag : spring , By : FriendL
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • JUnit vs TestNG
  • Are there any decent free Java data plotting libraries out there?
  • Java Time Zone is messed up
  • Eclipse on win64
  • Automate builds for Java RCP for deployment with JNLP
  • Is there a real benefit of using J#?
  • Why can't I use a try block around my super() call?
  • Accessing post variables using Java Servlets
  • Is this really widening vs autoboxing?
  • How can I Java webstart multiple, dependent, native libraries?
  • Why doesn't Java autoboxing extend to method invocations of methods of the autoboxed types?
  • How do I use Java to read from a file that is actively being written to?
  • What code analysis tools do you use for your Java projects?
  • IllegalArgumentException or NullPointerException for a null parameter?
  • How do I configure and communicate with a serial port?
  • What are the different methods to parse strings in Java?
  • Android Broadcastreceiver for other apps install/delete not working
  • Android Studio onClick not working in BindViewHolder
  • How verify that 3 numbers in sequence are equals?
  • When using .compareTo to compare dates, why doesn't it take Months into account?
  • Does the perfomance of "filter then map" and "map then filter" differ in a Stream?
  • How can I set the initial Delay after pressing the start Button to a specific time (HH:mm:ss) format
  • How to switch between Android devices during the tests
  • How to configure java.util.logging via properties to use standard output?
  • How to iterate through array in order
  • Is there better way of iteration to find the evenly divisible number?
  • How do I avoid using if statements with a large amount of variables in java
  • Writing JUnit test cases for a Spring Boot Service Application with autowired components
  • Cors for GET with Postman not showing headers
  • Printing values in different column same row using APACHE POI
  • Fully decompile java6 web application
  • Passing keycloak configuration parameters in the code rather than reading from application.properties
  • setDataSource() IO exception
  • Unexpected Output while retrieving Data from mongodb and displaying in a csv file?
  • Algorithm for searching a value in two arrays
  • How to avoid casting with generic return values?
  • Java/RegEx - Negation of pattern not working
  • How to split a string to non empty words if it might include a separator like tab on first place
  • Supplier<Sequence<String>> cannot be iterated more than once
  • Why there is only one thread can actually started in @PostConstruct method?
  • Manage CompletionStage inside of Netty handler
  • Url Problem while Developing on Localhost and deploy on Remote Virtual Server
  • How to identify the missing type id in Jackson error?
  • android data binding error: cannot find symbol
  • Spring Boot application with a jar dependency does not run after maven build
  • Spring Data JPA query , filter ? search engine ? JPQL?
  • Why LiveData returns null in ViewModel?
  • what this line of code mean....new URLClassLoader(new URL[0],getClass().getClassLoader());
  • Why do need to use new Random() instead of just Random Randomnum?
  • I want to access zk components from the java file
  • How do I cast FieldValue.serverTimestamp() to Kotlin/Java Date Class
  • Insertion Sort Double Array with User Input - JAVA
  • Creating 2 dimesional array with user input and find sum of specific columns
  • can not get Advertising ID Provider in android
  • Convert list of Objects to map of properties
  • How to represent an undirected weighted graph in java
  • Return values as array from collection
  • ByteBuddy generic method return cast to concrete type
  • ImageView hides the round corners of the parent
  • Is there a way to find setter method by its getter method or vice versa in a class?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com