001/*
002 * Copyright 2012-2018 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.boot.context.properties;
018
019import org.springframework.beans.factory.BeanCreationException;
020import org.springframework.util.ClassUtils;
021
022/**
023 * Exception thrown when {@link ConfigurationProperties @ConfigurationProperties} binding
024 * fails.
025 *
026 * @author Phillip Webb
027 * @author Stephane Nicoll
028 * @since 2.0.0
029 */
030public class ConfigurationPropertiesBindException extends BeanCreationException {
031
032        private final Class<?> beanType;
033
034        private final ConfigurationProperties annotation;
035
036        ConfigurationPropertiesBindException(String beanName, Object bean,
037                        ConfigurationProperties annotation, Exception cause) {
038                super(beanName, getMessage(bean, annotation), cause);
039                this.beanType = bean.getClass();
040                this.annotation = annotation;
041        }
042
043        /**
044         * Return the bean type that was being bound.
045         * @return the bean type
046         */
047        public Class<?> getBeanType() {
048                return this.beanType;
049        }
050
051        /**
052         * Return the configuration properties annotation that triggered the binding.
053         * @return the configuration properties annotation
054         */
055        public ConfigurationProperties getAnnotation() {
056                return this.annotation;
057        }
058
059        private static String getMessage(Object bean, ConfigurationProperties annotation) {
060                StringBuilder message = new StringBuilder();
061                message.append("Could not bind properties to '"
062                                + ClassUtils.getShortName(bean.getClass()) + "' : ");
063                message.append("prefix=").append(annotation.prefix());
064                message.append(", ignoreInvalidFields=").append(annotation.ignoreInvalidFields());
065                message.append(", ignoreUnknownFields=").append(annotation.ignoreUnknownFields());
066                return message.toString();
067        }
068
069}