简体   繁体   中英

How to validate annotated with Spring @Value field using custom annotation?

How can i check if "${path}" value is not empty or is correct path and if so, throw some exception? I want to it happen during Bean creation. All I found that is such validation used in multilayer apps for user input data validation in @Controller classes with using @Valid annotation. But what i did was not working.

It a simple Spring app, that reading application.properties and somehow processes them. Here is my code:

@Component
public class ParseService {

@Value("${path}")
@PathValue
private String path;
}

@Documented
@Constraint(validatedBy = PathValidatorImpl.class)
@Retention(RUNTIME)
@Target({ElementType.FIELD})
public @interface PathValue {

  String message() default "Is empty or not valid path!"; 
}

public class PathValidatorImpl implements ConstraintValidator<PathValue, 
String> {

  @Override
  public void initialize(PathValue pathValue) {
  }

  @Override
  public boolean isValid(String path, ConstraintValidatorContext ctx) {
  if (path.isEmpty() || !(new File(path).exists())) {
     return false;
    } else
     return true;
    }
 }

Can I do this and if so, What am I doing wrong?

I tried this:

@Component
public class FileGuider {
public List<File> search(@Valid String path, String sourceFileExtension)
  throws IOException, NoFilesToParseException {...}

PS I use Spring in this app for studying.

Here you find an example

Controller

import javax.validation.Valid; //Import this Class for valid annotation
 @RequestMapping(value = CommonConstants.TOKEN_CREATION , method = RequestMethod.POST)
    public ResponseJson tokenCreation(@Valid @RequestBody LoginReq loginReq) {
        response.setResponse(authenticationService.authenticateUser(loginReq));
        return response;
    }

Next LoginReq Request class with validation

import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
public class LoginReq {
    @NotEmpty 
    @Email(message ="{NotEmpty.user.email}")
    private String userEmail;
    @NotEmpty
    @Size(min=8, message="{NotEmpty.user.password}")
    private String userCredential;
    public String getUserEmail() {
        return userEmail;
    }
    public void setUserEmail(String userEmail) {
        this.userEmail = userEmail;
    }
    public String getUserCredential() {
        return userCredential;
    }
    public void setUserCredential(String userCredential) {
        this.userCredential = userCredential;
    }
}

For more information GitHubLink . if you have still problem feel free and ask here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM