I have created a java service to get the details from dynamodb it is working fine but my challenge is i hardcoded the table name to the class file #DynamoDbTable annotation in order to work with different environments i feel it is not the right way. I have given my code below could someone help me to resolve the issue.
Code sample
public class DynamodbService {
private DynamoDB client;
private DynamoDBMapper objectMapper;
/**
*
* #param client
* #param objectMapper
*/
#Autowired
public DynamodbService(DynamoDB client, DynamoDBMapper objectMapper) {
this.client = client;
this.objectMapper = objectMapper;
}
public List<Dynamodb> findAll() throws Exception {
DynamoDBMapperConfig mapperConfig = new DynamoDBMapperConfig.Builder()
.withTableNameOverride(DynamoDBMapperConfig.TableNameOverride.withTableNameReplacement(""))
.build();
DynamoDBMapper mapper = new DynamoDBMapper(client, mapperConfig);
DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
List<Dynamodb> scanResult = objectMapper.scan(Dynamodb.class, scanExpression);
return scanResult;
}
}
My DynamoDB config
#Configuration
public class DynamoDBconfig {
/**
*
*/
#Value("${amazon.dynamodb.accesskey}")
private String awsAccessKey;
/**
*
*/
#Value("${amazon.dynamodb.secretkey}")
private String awsSecretKey;
#Bean
public AWSCredentials amazonAWSCredentials() {
return new BasicAWSCredentials(aes.getDecryptedvalue(awsAccessKey), aes.getDecryptedvalue(awsSecretKey));
}
/**
*
* #return
*/
#Bean
public DynamoDBMapperConfig dynamoDBMapperConfig() {
return DynamoDBMapperConfig.DEFAULT;
}
/**
*
* #param amazonDynamoDB
* #param config
* #return
*/
#Bean
public DynamoDBMapper dynamoDBMapper(AmazonDynamoDB amazonDynamoDB, DynamoDBMapperConfig config) {
return new DynamoDBMapper(amazonDynamoDB, config);
}
/**
*
* #return
*/
#Bean
public AmazonDynamoDB amazonDynamoDB() {
return AmazonDynamoDBClientBuilder.standard().withCredentials(amazonAWSCredentialsProvider())
.withRegion(Regions.US_EAST_2).build();
}
/**
*
* #return
*/
#Bean
public DynamoDB dynamoDB() {
return new DynamoDB(amazonDynamoDB());
}
/**
*
* #return
*/
public AWSCredentialsProvider amazonAWSCredentialsProvider() {
return new AWSStaticCredentialsProvider(amazonAWSCredentials());
}
}
ERROR in my dynamodb service
The constructor DynamoDBMapper(DynamoDB, DynamoDBMapperConfig) is undefined
I am unable find out what is the issue. If i use table name in class file it's working fine if i try to replace the table name using code it ends up with error.
DynamoDBMapper expects any implementation of AmazonDynamoDB but not DynamoDB class.
public DynamoDBMapper(
final AmazonDynamoDB dynamoDB,
final DynamoDBMapperConfig config) {
You need to inject only the DynamoDBMapper in your service.
#Bean
public DynamoDBMapper dynamoDBMapper(AmazonDynamoDB amazonDynamoDB) {
DynamoDBMapperConfig config = new DynamoDBMapperConfig.Builder().withTableNameOverride(TableNameOverride.withTableNameReplacement(tableName))
.build();
return new DynamoDBMapper(amazonDynamoDB, config);
}
Other option could be using com.amazonaws.services.dynamodbv2.document.DynamoDB class but there you could not use DynamoDBScanExpression and you need to rewrite your code.
String desiredTabledName = "table-name";
Table table = dynamoDB.getTable(desiredTabledName);
You have multiple options.
- table.scan() and table query.
- Index index = table.getIndex(indexName);
index.scan() or index.query()
- You could pass `QuerySpec` and `ScanSpec` to all above.
Related
There is a ClassCastException when reading data from reids, but the actual quantity type is correct, and this happens for a period of time. After restarting the service, the problem is solved, but it appears again in some days!
``` #Configuration
public class RedisConfig {
/**
* FastJson序列化
*
* #param factory
* #return
* #author Hes
*/
#Bean
public RedisTemplate fastJsonRedisTemplate(RedisConnectionFactory factory) throws Exception {
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(factory);
FastJsonSerializer serializer = new FastJsonSerializer<Object>(Object.class);
redisTemplate.setValueSerializer(serializer);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
/**
* fst序列化
*
* #param factory
* #return
* #author Hes
*/
#Bean
public RedisTemplate<String, Object> fstRedisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
FSTSerializer<Object> serializer = new FSTSerializer<>();
redisTemplate.setDefaultSerializer(serializer);
redisTemplate.setKeySerializer(RedisSerializer.string());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
public static List<DataMap> search(String orgNo) {
List<DataMap> datas = RedisKit.getMapValue(CACHE_AREA, orgNo);
return datas;
}
public static <T> T getMapValue(String cacheKey, String valueKey) {
T t = null;
if (StrUtil.isNotBlank(cacheKey) && redisTemplate != null) {
t = (T) redisTemplate.opsForHash().get(cacheKey, valueKey);
}
return t;
}
```
** 2022-02-23 09:01:08.405 [http-nio-22000-exec-6] ERROR com.hnmqet.framework.exception.ExceptionCatch - catch exception:java.lang.ClassCastException: java.lang.String cannot be cast to java.util.List
at com.hnmqet.framework.cache.AreaCache.search(AreaCache.java:17)
at com.hnmqet.jail.base.service.area.impl.AreaMainServiceImpl.listAreaMain(AreaMainServiceImpl.java:83)
at com.hnmqet.jail.base.service.area.impl.AreaMainServiceImpl.listAreaGroup(AreaMainServiceImpl.java:161)
at com.hnmqet.jail.base.service.area.impl.AreaMainServiceImpl$$FastClassBySpringCGLIB$$6f19d178.invoke()**
Did you exactly find which "orgNo" cause this exception? If so, you should check the value in your hash map for related "orgNo" key. You can do it from CLI using this command by the way: https://redis.io/commands/hget/
I guess some test data was not written into Redis as expected.
Since SpringBoot 2.2.2, the custom pagination serializer with Jackson (2.10.1) doesn't work and isn't executed when serializing.
/**
* This class allows to specify configuration related to the Web MVC part.
*/
#Configuration
public class WebConfiguration implements WebMvcConfigurer {
private static final String JSON_DATA_PROPERTY = "data";
/**
* Allows to configure a {#link JsonSerializer} for pagination.
*
* #return an instance of {#link Module}.
*/
#SuppressWarnings("rawtypes")
#Bean
public Module springDataPageModule() {
return new SimpleModule().addSerializer(Page.class, new JsonSerializer<Page>() {
#Override
public void serialize(final Page page, final JsonGenerator jsonGenerator,
final SerializerProvider serializers) throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField(JSON_DATA_PROPERTY, page.getContent());
jsonGenerator.writeObjectFieldStart("paging");
jsonGenerator.writeNumberField("page", page.getNumber() + 1);
jsonGenerator.writeNumberField("totalPages", page.getTotalPages());
jsonGenerator.writeNumberField("totalElements", page.getTotalElements());
jsonGenerator.writeNumberField("perPage", page.getSize());
jsonGenerator.writeEndObject();
jsonGenerator.writeEndObject();
}
});
}
...
}
With SpringBoot 2.2.1, this custom pagination serializer is applied and works.
Can you see this problem ?
The behavior has changed since SpringBoot 2.2.2.
You have to go through the registration of the module
/**
* This class allows to specify configuration related to the Web MVC part.
*/
#Configuration
public class WebConfiguration implements WebMvcConfigurer {
private static final String JSON_DATA_PROPERTY = "data";
/**
* Allows to configure a {#link JsonSerializer} for pagination.
*
* #return an instance of {#link Module}.
*/
private Module preparePageModule() {
return new SimpleModule().addSerializer(Page.class, new JsonSerializer<>() {
#Override
public void serialize(#SuppressWarnings("rawtypes") final Page page, final JsonGenerator jsonGenerator,
final SerializerProvider serializers) throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField(JSON_DATA_PROPERTY, page.getContent());
jsonGenerator.writeObjectFieldStart("paging");
jsonGenerator.writeNumberField("page", page.getNumber() + 1);
jsonGenerator.writeNumberField("totalPages", page.getTotalPages());
jsonGenerator.writeNumberField("totalElements", page.getTotalElements());
jsonGenerator.writeNumberField("perPage", page.getSize());
jsonGenerator.writeEndObject();
jsonGenerator.writeEndObject();
}
});
}
/**
* Allows to configure the Jackson object mapper.
*
* #param objectMapper
* an instance of {#link ObjectMapper}.
*/
#Autowired
public void configureJacksonObjectMapper(final ObjectMapper objectMapper) {
...
objectMapper.registerModule(preparePageModule());
}
...
}
`
I plan on writing a query method like
/**
* TODO Auto-generated method documentation
*
* #param entity
* #return EventExecute
*/
#Transactional
#Autowired
public EventExecute save(EventExecute entity) {
String eventKey = entity.getEventKey();
StepDefinitionRepository sdRepository;
List<StepDefinition> stepDefinitions = sdRepository.findByEventKeyAllIgnoreCaseOrderBySequenceAsc(eventKey);
return getEventExecuteRepository().save(entity);
}
I want to lookup the StepDefintions that match an event key.
I tried following the example in the JPA Documentation...
public class SomeClient {
#Autowired
private PersonRepository repository;
public void doSomething() {
List<Person> persons = repository.findByLastname("Matthews");
}
}
But my sdRepository complains that is it not initialized. I found the getStepDefintionRepository() in the ..ServiceImpl.aj but can't call it.
Is there an example out there?
Ok I figured out my error...here is what works.
#Autowired
private StepDefinitionRepository sdRepository;
/**
* Overridden save method to intercept and process the dynamic steps before saving
*
* #param entity
* #return EventExecute
*/
#Transactional
public EventExecute save(EventExecute entity) {
boolean keepGoing = true;
String eventKey = entity.getEventKey();
Set<NameValuePair> messageVariables = null;
String eventArguments = entity.getEventArguments();
List<NameValuePair> eventVariables = null;
if (!eventArguments.isEmpty()){
eventVariables = _ExtractEventVariables(eventArguments);
}
List<StepDefinition> stepDefinitions = sdRepository.findByEventKeyAllIgnoreCaseOrderBySequenceAsc(eventKey);
for (Iterator<StepDefinition> iterator = stepDefinitions.iterator(); iterator.hasNext();) {
I am newbie to spring-data-rest. In my Application when i make a rest call i am getting json which consist on self-links and links to foreign key tables. But i want json instead on links. I generated my code using telosys tool generator. Here is my JSON what i am gettin when i made a REST call to the "merchandise" table in database.:
{
"id" : 1,
"rate": 300,
"type": "item",
"shortDescription": "test",
"longDescription": "test test",
"_links": {
"self": {
"href": "http://localhost:8080/sportsrest/merchandises/1"
},
"listOfMerchandiseAttribute": {
"href": "http://localhost:8080/sportsrest/merchandises/1/listOfMerchandiseAttribute"
},
}
}
But in instead of getting link of "listOfMerchandiseAttribute" i want to get JSON of listOfMerchandiseAttribute. listOfMerchandiseAttribute is my another table in database
That is i want my json like this:
{
"id": 1,
"rate": 300,
"type": "item",
"shortDescription": "test",
"longDescription": "test test",
"_links": {
"self": {
"href": "http://localhost:8080/sportsrest/merchandises/1"
},
"listOfMerchandiseAttribute": {
"id": 1,
"attributeName": "testname",
"attributeValue": 50
},
}
}
When i search on google i got some results and changed the ApplicationConfig.java file according to that but still i am getting links instead of JSON. Here is My ApplicationConfig file.
ApplicationConfig.java
/*
* Created on 19 Mar 2015 ( Time 14:41:07 )
* Generated by Telosys Tools Generator ( version 2.1.0 )
*/
package co.vitti.sports;
import org.springframework.context.MessageSource;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
import org.springframework.http.MediaType;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import co.vitti.sports.validator.BinaryValidator;
import co.vitti.sports.validator.CustomerPackageBalValidator;
import co.vitti.sports.validator.MerchandiseItemValidator;
import co.vitti.sports.validator.CustomerPackageValidator;
import co.vitti.sports.validator.InvoiceValidator;
import co.vitti.sports.validator.UserRoleValidator;
import co.vitti.sports.validator.SportValidator;
import co.vitti.sports.validator.MerchandiseTypeValidator;
import co.vitti.sports.validator.BookingValidator;
import co.vitti.sports.validator.TenantValidator;
import co.vitti.sports.validator.PaymentModeValidator;
import co.vitti.sports.validator.CourtValidator;
import co.vitti.sports.validator.MerchandisePackageValidator;
import co.vitti.sports.validator.CartValidator;
import co.vitti.sports.validator.MigrationValidator;
import co.vitti.sports.validator.TenantSportValidator;
import co.vitti.sports.repository.converter.TenantSportKeyConverter;
import co.vitti.sports.validator.TenantPaymentmodeValidator;
import co.vitti.sports.repository.converter.TenantPaymentmodeKeyConverter;
import co.vitti.sports.validator.MerchandiseAttributeValidator;
import co.vitti.sports.repository.converter.MerchandiseAttributeKeyConverter;
import co.vitti.sports.validator.CartItemValidator;
import co.vitti.sports.validator.MerchandiseValidator;
import co.vitti.sports.validator.UserValidator;
import co.vitti.sports.validator.TimeslotValidator;
import co.vitti.sports.validator.RoleValidator;
import org.springframework.core.convert.support.ConfigurableConversionService;
/**
* Application configuration.
* ( messages resources, validators)
* #author Telosys Tools Generator
*
*/
#Configuration
#ComponentScan(basePackageClasses = ApplicationConfig.class)
#EnableWebMvc
public class ApplicationConfig extends RepositoryRestMvcConfiguration {
#Override
protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config){
config.setDefaultMediaType((MediaType) MediaType.parseMediaTypes("application/x-spring-data-verbose+json"));
}
#Bean
public DataSource dataSource(){
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.HSQL).build();
}
/**
* Message Ressource declaration.
* #return MessageRessource
*/
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasename("i18n/messages");
source.setUseCodeAsDefaultMessage(true);
return source;
}
/**
* Validator declaration for Binary
* #return the BinaryValidator
*/
#Bean
public BinaryValidator beforeCreateBinaryValidator() {
return new BinaryValidator();
}
/**
* Validator declaration for CustomerPackageBal
* #return the CustomerPackageBalValidator
*/
#Bean
public CustomerPackageBalValidator beforeCreateCustomerPackageBalValidator() {
return new CustomerPackageBalValidator();
}
/**
* Validator declaration for MerchandiseItem
* #return the MerchandiseItemValidator
*/
#Bean
public MerchandiseItemValidator beforeCreateMerchandiseItemValidator() {
return new MerchandiseItemValidator();
}
/**
* Validator declaration for CustomerPackage
* #return the CustomerPackageValidator
*/
#Bean
public CustomerPackageValidator beforeCreateCustomerPackageValidator() {
return new CustomerPackageValidator();
}
/**
* Validator declaration for Invoice
* #return the InvoiceValidator
*/
#Bean
public InvoiceValidator beforeCreateInvoiceValidator() {
return new InvoiceValidator();
}
/**
* Validator declaration for UserRole
* #return the UserRoleValidator
*/
#Bean
public UserRoleValidator beforeCreateUserRoleValidator() {
return new UserRoleValidator();
}
/**
* Validator declaration for Sport
* #return the SportValidator
*/
#Bean
public SportValidator beforeCreateSportValidator() {
return new SportValidator();
}
/**
* Validator declaration for MerchandiseType
* #return the MerchandiseTypeValidator
*/
#Bean
public MerchandiseTypeValidator beforeCreateMerchandiseTypeValidator() {
return new MerchandiseTypeValidator();
}
/**
* Validator declaration for Booking
* #return the BookingValidator
*/
#Bean
public BookingValidator beforeCreateBookingValidator() {
return new BookingValidator();
}
/**
* Validator declaration for Tenant
* #return the TenantValidator
*/
#Bean
public TenantValidator beforeCreateTenantValidator() {
return new TenantValidator();
}
/**
* Validator declaration for PaymentMode
* #return the PaymentModeValidator
*/
#Bean
public PaymentModeValidator beforeCreatePaymentModeValidator() {
return new PaymentModeValidator();
}
/**
* Validator declaration for Court
* #return the CourtValidator
*/
#Bean
public CourtValidator beforeCreateCourtValidator() {
return new CourtValidator();
}
/**
* Validator declaration for MerchandisePackage
* #return the MerchandisePackageValidator
*/
#Bean
public MerchandisePackageValidator beforeCreateMerchandisePackageValidator() {
return new MerchandisePackageValidator();
}
/**
* Validator declaration for Cart
* #return the CartValidator
*/
#Bean
public CartValidator beforeCreateCartValidator() {
return new CartValidator();
}
/**
* Validator declaration for Migration
* #return the MigrationValidator
*/
#Bean
public MigrationValidator beforeCreateMigrationValidator() {
return new MigrationValidator();
}
/**
* Validator declaration for TenantSport
* #return the TenantSportValidator
*/
#Bean
public TenantSportValidator beforeCreateTenantSportValidator() {
return new TenantSportValidator();
}
/**
* Validator declaration for TenantPaymentmode
* #return the TenantPaymentmodeValidator
*/
#Bean
public TenantPaymentmodeValidator beforeCreateTenantPaymentmodeValidator() {
return new TenantPaymentmodeValidator();
}
/**
* Validator declaration for MerchandiseAttribute
* #return the MerchandiseAttributeValidator
*/
#Bean
public MerchandiseAttributeValidator beforeCreateMerchandiseAttributeValidator() {
return new MerchandiseAttributeValidator();
}
/**
* Validator declaration for CartItem
* #return the CartItemValidator
*/
#Bean
public CartItemValidator beforeCreateCartItemValidator() {
return new CartItemValidator();
}
/**
* Validator declaration for Merchandise
* #return the MerchandiseValidator
*/
#Bean
public MerchandiseValidator beforeCreateMerchandiseValidator() {
return new MerchandiseValidator();
}
/**
* Validator declaration for User
* #return the UserValidator
*/
#Bean
public UserValidator beforeCreateUserValidator() {
return new UserValidator();
}
/**
* Validator declaration for Timeslot
* #return the TimeslotValidator
*/
#Bean
public TimeslotValidator beforeCreateTimeslotValidator() {
return new TimeslotValidator();
}
/**
* Validator declaration for Role
* #return the RoleValidator
*/
#Bean
public RoleValidator beforeCreateRoleValidator() {
return new RoleValidator();
}
/**
* Add all converters for composite keys
*/
#Override
protected void configureConversionService(ConfigurableConversionService conversionService) {
super.configureConversionService(conversionService);
conversionService.addConverter(this.tenantsportKeyConverter());
conversionService.addConverter(this.tenantpaymentmodeKeyConverter());
conversionService.addConverter(this.merchandiseattributeKeyConverter());
}
/**
* Converter for the composite key in the TenantSport entity
* #return the converter
*/
#Bean
public TenantSportKeyConverter tenantsportKeyConverter() {
return new TenantSportKeyConverter();
}
/**
* Converter for the composite key in the TenantPaymentmode entity
* #return the converter
*/
#Bean
public TenantPaymentmodeKeyConverter tenantpaymentmodeKeyConverter() {
return new TenantPaymentmodeKeyConverter();
}
/**
* Converter for the composite key in the MerchandiseAttribute entity
* #return the converter
*/
#Bean
public MerchandiseAttributeKeyConverter merchandiseattributeKeyConverter() {
return new MerchandiseAttributeKeyConverter();
}
// equivalents for <mvc:resources/> tags
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/app/**").addResourceLocations("/app/")
.setCachePeriod(31556926);
}
// equivalent for <mvc:default-servlet-handler/> tag
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Can anyone please help me to solve my issue and get the JSON instead on links.
Thanks in Advance.
You should make sure that listOfMerchandiseAttribute is a member of your domain class. Then default converting to JSON should have it there.
And Spring Data REST will use what-ever you current representation is and add Hypermedia.
See also Disable Hypertext Application Language (HAL) in JSON?
You could use Excerpts (especially made for this scenario). Because the Spring example is so eloquent and it's silly to just copy it here I'll just point it: https://docs.spring.io/spring-data/rest/docs/3.1.x/reference/html/#projections-excerpts.excerpting-commonly-accessed-data.
But just for the record and your convenience I'll paste the main parts of the spring example:
#Projection(name = "inlineAddress", types = { Person.class })
interface InlineAddress {
String getFirstName();
String getLastName();
Address getAddress();
}
see at Projection javadoc that types means The type the projection type is bound to.
The excerpt could be used this way:
#RepositoryRestResource(excerptProjection = InlineAddress.class)
interface PersonRepository extends CrudRepository<Person, Long> {}
in order to get this:
{
"firstName" : "Frodo",
"lastName" : "Baggins",
"address" : {
"street": "Bag End",
"state": "The Shire",
"country": "Middle Earth"
},
"_links": ...
}
For you merchandise is the equivalent of Person and the listOfMerchandiseAttribute is the equivalent of address.
How to get rid of _links
Check my answer at Disable Hypertext Application Language (HAL) in JSON?.
Final notes
Spring is evolving so be aware that this works with at least:
spring-data-rest-webmvc 3.1.3.RELEASE
or, if you prefeer spring boot version:
spring-boot-starter-parent 2.1.1.RELEASE
A cleaner way to do it would be to set the following property to false in application.properties along with creating Projections
spring.hateoas.use-hal-as-default-json-media-type=false
HI I am using the following annotation based config ,to wire up my aspect which looks on the spring controllers for logging and other cross cutting method calls.But it seems the code I am using is not getting invoked .
#Configuration
#EnableWebMvc
#EnableAspectJAutoProxy
#ComponentScan({"com.pumpkinsafari.api"})
public class WebConfig extends WebMvcConfigurerAdapter {
/** The Constant DD_MM_YYYY. */
private static final String DD_MM_YYYY = "yyyy-MM-dd";
/** The Constant DATE_FORMAT. */
private static final DateFormat DATE_FORMAT = new SimpleDateFormat(DD_MM_YYYY);
/**
* Instantiates a new web config.
*/
public WebConfig() {
super();
}
#Bean
public RestControllerAspect controllerAspect(){
return new RestControllerAspect();
}
// beans
/**
* Xstream marshaller.
*
* #return the x stream marshaller
*/
public XStreamMarshaller xstreamMarshaller() {
final XStreamMarshaller xStreamMarshaller = new XStreamMarshaller();
xStreamMarshaller.setAutodetectAnnotations(true);
xStreamMarshaller.setAnnotatedClasses(new Class[] { Principal.class, Customer.class, Role.class,
Privilege.class, SocialUser.class, SearchRequest.class });
xStreamMarshaller.getXStream().addDefaultImplementation(java.sql.Timestamp.class, java.util.Date.class);
return xStreamMarshaller;
}
/**
* Marshalling http message converter.
*
* #return the marshalling http message converter
*/
public MarshallingHttpMessageConverter marshallingHttpMessageConverter() {
final MarshallingHttpMessageConverter marshallingHttpMessageConverter = new MarshallingHttpMessageConverter();
final XStreamMarshaller xstreamMarshaller = xstreamMarshaller();
marshallingHttpMessageConverter.setMarshaller(xstreamMarshaller);
marshallingHttpMessageConverter.setUnmarshaller(xstreamMarshaller);
return marshallingHttpMessageConverter;
}
// template
/*
* (non-Javadoc)
*
* #see
* org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
* #configureMessageConverters(java.util.List)
*/
#Override
public void configureMessageConverters(final List<HttpMessageConverter<?>> messageConverters) {
messageConverters.add(marshallingHttpMessageConverter());
final ClassLoader classLoader = getClass().getClassLoader();
if (ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader)) {
MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
jackson2HttpMessageConverter.getObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// Register date format for marshalling unmarshalling dates
jackson2HttpMessageConverter.getObjectMapper().setDateFormat(DATE_FORMAT);
messageConverters.add(jackson2HttpMessageConverter);
} else if (ClassUtils.isPresent("org.codehaus.jackson.map.ObjectMapper", classLoader)) {
MappingJacksonHttpMessageConverter jacksonHttpMessageConverter = new MappingJacksonHttpMessageConverter();
jacksonHttpMessageConverter.getObjectMapper().disable(
DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
// Register date format for marshalling unmarshalling dates
jacksonHttpMessageConverter.getObjectMapper().setDateFormat(DATE_FORMAT);
messageConverters.add(jacksonHttpMessageConverter);
}
super.configureMessageConverters(messageConverters);
}
}
but my aspect is not getting invoked ..The aspect class is as below
#Aspect
public class RestControllerAspect {
#Pointcut("within(#org.springframework.stereotype.Controller *)")
public void controller() {
}
#Pointcut("execution(* *(..))")
public void methodPointcut() {
System.out.println("Invoked: ");
}
#Pointcut("within(#org.springframework.web.bind.annotation.RequestMapping *)")
public void requestMapping() {
System.out.println("Invoked: ");
}
#Before("controller() && methodPointcut() && requestMapping()")
public void aroundControllerMethod(JoinPoint joinPoint) throws Throwable {
System.out.println("Invoked: " + niceName(joinPoint));
}
#AfterReturning("controller() && methodPointcut() && requestMapping()")
public void afterControllerMethod(JoinPoint joinPoint) {
System.out.println("Finished: " + niceName(joinPoint));
}
private String niceName(JoinPoint joinPoint) {
return joinPoint.getTarget().getClass() + "#" + joinPoint.getSignature().getName() + "\n\targs:"
+ Arrays.toString(joinPoint.getArgs());
}
}
Please HELP SOMEONE !!!
Change Your #Pointcut definitions. For types instead of within(#.... use #within(...., for methods instead of within(#.... use #annotation(....
See spring referene regarding pointcuts for more info