'Accessing application property in Spring boot application from MapStruct mapper
I want to access basic-info.expiration
from application.yml
a Spring boot application.
application.yml
basic-info:
expiration: 6
UserMapper.java
@Mapper(componentModel = "spring")
public interface UserMapper {
@Value("${basic-info.expiration}")
static long expireInMonths = 0;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^
@Mapping(target = "requireBasicInfoUpdate", source = "user", qualifiedByName = "isBasicInfoUpdateRequired")
UserDto toUserDto(User user);
@Named("isBasicInfoUpdateRequired")
default Boolean isBasicInfoUpdateRequired(User user) {
final var expireDate = LocalDate.now().minusMonths(expireInMonths);
final var lastUpdatedOn = user.getBasicInfoUpdatedDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
return expireDate.isAfter(lastUpdatedOn);
}
}
How to inject property value with MapStruct
Solution 1:[1]
As @M. Deinum suggested, interface was changed to an abstract class. This is the most preferred method since application need no refactoring.
@Mapper(componentModel = "spring")
public abstract class UserMapper {
@Value("${basic-info.expiration}")
long expireInMonths = 0;
@Mapping(target = "requireBasicInfoUpdate", source = "user", qualifiedByName = "isBasicInfoUpdateRequired")
public abstract UserDto toUserDto(User user);
@Named("isBasicInfoUpdateRequired")
public Boolean isBasicInfoUpdateRequired(User user) {
final var expireDate = LocalDate.now().minusMonths(expireInMonths);
final var lastUpdatedOn = user.getBasicInfoUpdatedDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
return expireDate.isAfter(lastUpdatedOn);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | s1n7ax |