Spring spring JSR303非Spring弹簧托管bean的Bean验证

时间:2016-06-01 13:33:01

标签: java spring spring-boot bean-validation

是否可以使用普通的spring-boot-starter项目实现JSR303 Bean验证,以下是我未能正常工作的源代码。

是否需要配置验证Bean,如果是这样我可以使用afterPropertiesSet进行验证但是如果在创建实例后修改属性以及如何修改属性,如何使其工作在不使用Validator实例的情况下让它适用于非Spring bean(无论何时在类中遇到注释,都会自动进行验证)

pom.xml片段

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <name>jsr303</name>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.5.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        ....
</project>

源代码

@Service
public class ProfileService {

public void createProfile( @Valid @NotEmpty  String name, @Valid @NotEmpty String email) {
            new Profile(
                    new EmailAddress(
                            "somasundarams@newemail.com"
                    ),
                    "Somasundaram S"
            );
        }
    }

Profile.java

public class Profile {

            private EmailAddress emailAddress;

            private String name;

            public Profile(@Valid @NotNull EmailAddress emailAddress, @Valid @NotEmpty  String name) {
                this.emailAddress = emailAddress;
                this.name = name;
            }
          .....
        }

EmailAddress.java

    public class EmailAddress {

        private String email;

        public EmailAddress(@Email String email) {
            this.email = email;
        }
     .....
    }

Jsr303Application.java

@SpringBootApplication
public class Jsr303Application {

    public static void main(String[] args) {

        ApplicationContext context =  SpringApplication.run(Jsr303Application.class, args);

        ProfileService profileService = context.getBean(ProfileService.class);

        profileService.createProfile(null, "Somasundaram S");
    }
}

0 个答案:

没有答案
相关问题