从 MapStruct 映射器访问 Spring 引导应用程序中的应用程序 属性
Accessing application property in Spring boot application from MapStruct mapper
我想从 application.yml
一个 Spring 引导应用程序访问 basic-info.expiration
。
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);
}
}
如何使用 MapStruct
注入 属性 值
作为@M。 Deinum 建议,接口已更改为抽象 class。这是最受欢迎的方法,因为应用程序不需要重构。
@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);
}
}
我想从 application.yml
一个 Spring 引导应用程序访问 basic-info.expiration
。
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);
}
}
如何使用 MapStruct
注入 属性 值作为@M。 Deinum 建议,接口已更改为抽象 class。这是最受欢迎的方法,因为应用程序不需要重构。
@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);
}
}