是否可以在填充Spring @Value之前运行验证代码

时间:2017-02-03 13:59:50

标签: java spring spring-mvc

我有弹簧MVC控制器

@Controller
@RequestMapping({ "/user/limits" })
public class UserController {

    @Value("${wsgServiceURL}")
    private String wsgServiceURL;
    .
    .

从属性文件

填充wsgServiceURL

可以在填充之前对该值运行验证代码

2 个答案:

答案 0 :(得分:2)

是的,可以通过@ConfigurationProperties机制

使用类型安全配置属性
@Controller
@RequestMapping({ "/user/limits" })
@ConfigurationProperties("uc") 
public class UserController {
     // will map to uc.wsgServiceURL in property file
    private String wsgServiceURL;

您还可以使用@Validated添加验证并使用JSR-303 javax.validation

答案 1 :(得分:1)

您可以执行以下操作,

@Controller
@RequestMapping({ "/user/limits" })
    public class UserController {

        private String wsgServiceURL;

        @Autowired
        public void initProperty(@Value("${wsgServiceURL}") String wsgServiceURL) {
            if(wsgServiceURL== null) {
                // Error handling here
            }
        }
    }