@ConfigurationProperties和不可解析的属性

时间:2017-03-06 17:01:03

标签: java spring spring-boot properties

假设以下配置bean:

@ConfigurationProperties(prefix="foo")
private class FooProperties {
   private String mystring;
   private int myint;
}

以及以下application.properties

foo.mystring = ${bar.mystring}
foo.myint    = ${bar.myint}

请注意,这两个属性是 unresolvable ,因为没有定义以bar开头的属性。以下是将要发生的事情:

  • foo.mystring设置为字符串"${bar.mystring}"(无解析)
  • foo.myint会导致转换错误,因为字符串"${bar.myint}"无法转换为有效整数。

我希望在这种情况下会抛出一种 Unresolvable Property 异常。就像我使用@Value("${foo.mystring}")时会发生什么。

预计会出现这种情况吗? 有没有办法让SpringBoot在这种情况下抛出这样的异常?

1 个答案:

答案 0 :(得分:0)

  

我希望有一种不可解析的属性例外   在这种情况下抛出。

def main(): conn = imaplib.IMAP4('SERVER') conn.login('username', 'passphrase') conn.select('inbox') (status, nums) = conn.search(None, '(UNSEEN)') msgnums = map(int, nums[0].split()) for i in msgnums: try: raw_msg = conn.fetch(i, '(RFC822)') raw_msg = conn.fetch(i, '(RFC822)') msg = email.message_from_string(raw_msg[1][0][1]) body = "Date: %s\r\nSender: %s\r\nSubject: %s\r\n\r\n" % (msg['Date'], msg['From'], msg['Subject']) msg_date = re.sub('/', '-', msg['Date']).replace(":", ".") fdate = re.sub('\s+', '_', msg_date).replace(",", "") print "Checking message: %s" % msg['Subject'] if not msg['Subject']: continue # fname = "unknown_msg%d_%s" % (i,fdate) elif msg['Subject'].lower().rfind('foobar') != -1: print "Subject match 'foobar', processing: %s" % msg['Subject'] # We should have from the pickle an "observed" set of data, both subjects and message numbers. if msg['Subject'] in PICKLED_MESSAGES['observed']['subjects']: print "Already handled this message, moving on to next item." # Since this was already observed we let it be removed so things don't rerun it later. # noinspection PyBroadException try: PICKLED_MESSAGES['observed']['subjects'].remove(msg['Subject']) PICKLED_MESSAGES['observed']['msgnums'].remove(i) except: pass continue else: continue # Do stuff with the message to store it in a special way on the filesystem # Note that we've now looked at the message, so next-run we can see # what was handled on the last run. PICKLED_MESSAGES['observed']['msgnums'].append(i) PICKLED_MESSAGES['observed']['subjects'].append(msg['Subject']) print "PICKLED:\n%s" % PICKLED_MESSAGES['observed'] conn.uid('STORE', str(i), '-FLAGS', '(\Seen)') except Exception: conn.uid('STORE', str(i), '-FLAGS', '(\Seen)') PICKLED_MESSAGES['observed']['msgnums'].remove(i) PICKLED_MESSAGES['observed']['subjects'].remove(msg['Subject']) print "PICKLED:\n%s\n" % PICKLED_MESSAGES finally: # Store the pickle file so we can use it next run. cPickle.dump(PICKLED_MESSAGES, open('observed_msgs.pkl', 'wb')) if __name__ == "__main__": # pre-runtime checks - is IMAP up, etc. run first, then this: # Initialize the PICKLED_MESSAGES data with pickle data or an empty # structure for the pickle. # noinspection PyBroadException try: PICKLED_MESSAGES = cPickle.load(open('observed_msgs.pkl', 'rb')) except Exception as e: PICKLED_MESSAGES = { 'observed': { 'msgnums': [], 'subjects': [], }, } # If all checks satisfied, continue and process the main() directives. try: main() except Exception as e: print("CRITICAL An unhandled error has occurred: %s" % str(e)) exit() 并没有抛出foo.myint,因为它正在通过Unresolvable Property exception解决,而当Spring尝试将${bar.myint}强制转换为String时,它会在下一步失败存储在int文件中的所有内容都是String值,除非您明确指定了它的类型,如下所示:

Properties
  

预期会出现这种情况吗?

可能是的。

  

在这种情况下,有没有办法让SpringBoot抛出这样的异常?

是的,对于foo.myint = (java.lang.Integer)${bar.myint} 级别,您可以使用@ControllerAdvice,如果您想使用Global级别,那么您可以使用@ExceptionHandler