Cannot instantiate the type Map String Boolean

Java Map实例化详解
本文详细解析了在Java中如何正确实例化Map接口,避免常见的编程错误,并提供了正确的实例化方式,即使用HashMap作为实现类。

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.youkuaiyun.com/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

无法实例化类型Map<String,Boolean>

错误代码:

Map<String, Boolean> modelPropertys = new Map<String, Boolean>();

看了一下Map的定义,public abstract interface java.util.Map

原来是抽象接口,不能直接实例化,需要使用它的实现类;

正确写法如下:

Map<String, Boolean> modelPropertys = new HashMap<String, Boolean>();


           

给我老师的人工智能教程打call!http://blog.youkuaiyun.com/jiangjunshow
这里写图片描述
'use strict' const { types, inspect } = require('node:util') const { markAsUncloneable } = require('node:worker_threads') const UNDEFINED = 1 const BOOLEAN = 2 const STRING = 3 const SYMBOL = 4 const NUMBER = 5 const BIGINT = 6 const NULL = 7 const OBJECT = 8 // function and object const FunctionPrototypeSymbolHasInstance = Function.call.bind(Function.prototype[Symbol.hasInstance]) /** @type {import('../../../types/webidl').Webidl} */ const webidl = { converters: {}, util: {}, errors: {}, is: {} } /** * @description Instantiate an error. * * @param {Object} opts * @param {string} opts.header * @param {string} opts.message * @returns {TypeError} */ webidl.errors.exception = function (message) { return new TypeError(`${message.header}: ${message.message}`) } /** * @description Instantiate an error when conversion from one type to another has failed. * * @param {Object} opts * @param {string} opts.prefix * @param {string} opts.argument * @param {string[]} opts.types * @returns {TypeError} */ webidl.errors.conversionFailed = function (opts) { const plural = opts.types.length === 1 ? '' : ' one of' const message = `${opts.argument} could not be converted to` + `${plural}: ${opts.types.join(', ')}.` return webidl.errors.exception({ header: opts.prefix, message }) } /** * @description Instantiate an error when an invalid argument is provided * * @param {Object} context * @param {string} context.prefix * @param {string} context.value * @param {string} context.type * @returns {TypeError} */ webidl.errors.invalidArgument = function (context) { return webidl.errors.exception({ header: context.prefix, message: `"${context.value}" is an invalid ${context.type}.` }) } // https://webidl.spec.whatwg.org/#implements webidl.brandCheck = function (V, I) { if (!FunctionPrototypeSymbolHasInstance(I, V)) { const err = new TypeError('Illegal invocation') err.code = 'ERR_INVALID_THIS' // node compat. throw err } } webidl.brandCheckMultiple = function (List) { const prototypes = List.map((c) => webidl.util.MakeTypeAssertion(c)) return (V) => { if (prototypes.every(typeCheck => !typeCheck(V))) { const err = new TypeError('Illegal invocation') err.code = 'ERR_INVALID_THIS' // node compat. throw err } } } webidl.argumentLengthCheck = function ({ length }, min, ctx) { if (length < min) { throw webidl.errors.exception({ message: `${min} argument${min !== 1 ? 's' : ''} required, ` + `but${length ? ' only' : ''} ${length} found.`, header: ctx }) } } webidl.illegalConstructor = function () { throw webidl.errors.exception({ header: 'TypeError', message: 'Illegal constructor' }) } webidl.util.MakeTypeAssertion = function (I) { return (O) => FunctionPrototypeSymbolHasInstance(I, O) } // https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values webidl.util.Type = function (V) { switch (typeof V) { case 'undefined': return UNDEFINED case 'boolean': return BOOLEAN case 'string': return STRING case 'symbol': return SYMBOL case 'number': return NUMBER case 'bigint': return BIGINT case 'function': case 'object': { if (V === null) { return NULL } return OBJECT } } } webidl.util.Types = { UNDEFINED, BOOLEAN, STRING, SYMBOL, NUMBER, BIGINT, NULL, OBJECT } webidl.util.TypeValueToString = function (o) { switch (webidl.util.Type(o)) { case UNDEFINED: return 'Undefined' case BOOLEAN: return 'Boolean' case STRING: return 'String' case SYMBOL: return 'Symbol' case NUMBER: return 'Number' case BIGINT: return 'BigInt' case NULL: return 'Null' case OBJECT: return 'Object' } } webidl.util.markAsUncloneable = markAsUncloneable || (() => {}) // https://webidl.spec.whatwg.org/#abstract-opdef-converttoint webidl.util.ConvertToInt = function (V, bitLength, signedness, flags) { let upperBound let lowerBound // 1. If bitLength is 64, then: if (bitLength === 64) { // 1. Let upperBound be 2^53 − 1. upperBound = Math.pow(2, 53) - 1 // 2. If signedness is "unsigned", then let lowerBound be 0. if (signedness === 'unsigned') { lowerBound = 0 } else { // 3. Otherwise let lowerBound be −2^53 + 1. lowerBound = Math.pow(-2, 53) + 1 } } else if (signedness === 'unsigned') { // 2. Otherwise, if signedness is "unsigned", then: // 1. Let lowerBound be 0. lowerBound = 0 // 2. Let upperBound be 2^bitLength − 1. upperBound = Math.pow(2, bitLength) - 1 } else { // 3. Otherwise: // 1. Let lowerBound be -2^bitLength − 1. lowerBound = Math.pow(-2, bitLength) - 1 // 2. Let upperBound be 2^bitLength − 1 − 1. upperBound = Math.pow(2, bitLength - 1) - 1 } // 4. Let x be ? ToNumber(V). let x = Number(V) // 5. If x is −0, then set x to +0. if (x === 0) { x = 0 } // 6. If the conversion is to an IDL type associated // with the [EnforceRange] extended attribute, then: if (webidl.util.HasFlag(flags, webidl.attributes.EnforceRange)) { // 1. If x is NaN, +∞, or −∞, then throw a TypeError. if ( Number.isNaN(x) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY ) { throw webidl.errors.exception({ header: 'Integer conversion', message: `Could not convert ${webidl.util.Stringify(V)} to an integer.` }) } // 2. Set x to IntegerPart(x). x = webidl.util.IntegerPart(x) // 3. If x < lowerBound or x > upperBound, then // throw a TypeError. if (x < lowerBound || x > upperBound) { throw webidl.errors.exception({ header: 'Integer conversion', message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.` }) } // 4. Return x. return x } // 7. If x is not NaN and the conversion is to an IDL // type associated with the [Clamp] extended // attribute, then: if (!Number.isNaN(x) && webidl.util.HasFlag(flags, webidl.attributes.Clamp)) { // 1. Set x to min(max(x, lowerBound), upperBound). x = Math.min(Math.max(x, lowerBound), upperBound) // 2. Round x to the nearest integer, choosing the // even integer if it lies halfway between two, // and choosing +0 rather than −0. if (Math.floor(x) % 2 === 0) { x = Math.floor(x) } else { x = Math.ceil(x) } // 3. Return x. return x } // 8. If x is NaN, +0, +∞, or −∞, then return +0. if ( Number.isNaN(x) || (x === 0 && Object.is(0, x)) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY ) { return 0 } // 9. Set x to IntegerPart(x). x = webidl.util.IntegerPart(x) // 10. Set x to x modulo 2^bitLength. x = x % Math.pow(2, bitLength) // 11. If signedness is "signed" and x ≥ 2^bitLength − 1, // then return x − 2^bitLength. if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) { return x - Math.pow(2, bitLength) } // 12. Otherwise, return x. return x } // https://webidl.spec.whatwg.org/#abstract-opdef-integerpart webidl.util.IntegerPart = function (n) { // 1. Let r be floor(abs(n)). const r = Math.floor(Math.abs(n)) // 2. If n < 0, then return -1 × r. if (n < 0) { return -1 * r } // 3. Otherwise, return r. return r } webidl.util.Stringify = function (V) { const type = webidl.util.Type(V) switch (type) { case SYMBOL: return `Symbol(${V.description})` case OBJECT: return inspect(V) case STRING: return `"${V}"` case BIGINT: return `${V}n` default: return `${V}` } } webidl.util.IsResizableArrayBuffer = function (V) { if (types.isArrayBuffer(V)) { return V.resizable } if (types.isSharedArrayBuffer(V)) { return V.growable } throw webidl.errors.exception({ header: 'IsResizableArrayBuffer', message: `"${webidl.util.Stringify(V)}" is not an array buffer.` }) } webidl.util.HasFlag = function (flags, attributes) { return typeof flags === 'number' && (flags & attributes) === attributes } // https://webidl.spec.whatwg.org/#es-sequence webidl.sequenceConverter = function (converter) { return (V, prefix, argument, Iterable) => { // 1. If Type(V) is not Object, throw a TypeError. if (webidl.util.Type(V) !== OBJECT) { throw webidl.errors.exception({ header: prefix, message: `${argument} (${webidl.util.Stringify(V)}) is not iterable.` }) } // 2. Let method be ? GetMethod(V, @@iterator). /** @type {Generator} */ const method = typeof Iterable === 'function' ? Iterable() : V?.[Symbol.iterator]?.() const seq = [] let index = 0 // 3. If method is undefined, throw a TypeError. if ( method === undefined || typeof method.next !== 'function' ) { throw webidl.errors.exception({ header: prefix, message: `${argument} is not iterable.` }) } // https://webidl.spec.whatwg.org/#create-sequence-from-iterable while (true) { const { done, value } = method.next() if (done) { break } seq.push(converter(value, prefix, `${argument}[${index++}]`)) } return seq } } // https://webidl.spec.whatwg.org/#es-to-record webidl.recordConverter = function (keyConverter, valueConverter) { return (O, prefix, argument) => { // 1. If Type(O) is not Object, throw a TypeError. if (webidl.util.Type(O) !== OBJECT) { throw webidl.errors.exception({ header: prefix, message: `${argument} ("${webidl.util.TypeValueToString(O)}") is not an Object.` }) } // 2. Let result be a new empty instance of record<K, V>. const result = {} if (!types.isProxy(O)) { // 1. Let desc be ? O.[[GetOwnProperty]](key). const keys = [...Object.getOwnPropertyNames(O), ...Object.getOwnPropertySymbols(O)] for (const key of keys) { const keyName = webidl.util.Stringify(key) // 1. Let typedKey be key converted to an IDL value of type K. const typedKey = keyConverter(key, prefix, `Key ${keyName} in ${argument}`) // 2. Let value be ? Get(O, key). // 3. Let typedValue be value converted to an IDL value of type V. const typedValue = valueConverter(O[key], prefix, `${argument}[${keyName}]`) // 4. Set result[typedKey] to typedValue. result[typedKey] = typedValue } // 5. Return result. return result } // 3. Let keys be ? O.[[OwnPropertyKeys]](). const keys = Reflect.ownKeys(O) // 4. For each key of keys. for (const key of keys) { // 1. Let desc be ? O.[[GetOwnProperty]](key). const desc = Reflect.getOwnPropertyDescriptor(O, key) // 2. If desc is not undefined and desc.[[Enumerable]] is true: if (desc?.enumerable) { // 1. Let typedKey be key converted to an IDL value of type K. const typedKey = keyConverter(key, prefix, argument) // 2. Let value be ? Get(O, key). // 3. Let typedValue be value converted to an IDL value of type V. const typedValue = valueConverter(O[key], prefix, argument) // 4. Set result[typedKey] to typedValue. result[typedKey] = typedValue } } // 5. Return result. return result } } webidl.interfaceConverter = function (TypeCheck, name) { return (V, prefix, argument) => { if (!TypeCheck(V)) { throw webidl.errors.exception({ header: prefix, message: `Expected ${argument} ("${webidl.util.Stringify(V)}") to be an instance of ${name}.` }) } return V } } webidl.dictionaryConverter = function (converters) { return (dictionary, prefix, argument) => { const dict = {} if (dictionary != null && webidl.util.Type(dictionary) !== OBJECT) { throw webidl.errors.exception({ header: prefix, message: `Expected ${dictionary} to be one of: Null, Undefined, Object.` }) } for (const options of converters) { const { key, defaultValue, required, converter } = options if (required === true) { if (dictionary == null || !Object.hasOwn(dictionary, key)) { throw webidl.errors.exception({ header: prefix, message: `Missing required key "${key}".` }) } } let value = dictionary?.[key] const hasDefault = defaultValue !== undefined // Only use defaultValue if value is undefined and // a defaultValue options was provided. if (hasDefault && value === undefined) { value = defaultValue() } // A key can be optional and have no default value. // When this happens, do not perform a conversion, // and do not assign the key a value. if (required || hasDefault || value !== undefined) { value = converter(value, prefix, `${argument}.${key}`) if ( options.allowedValues && !options.allowedValues.includes(value) ) { throw webidl.errors.exception({ header: prefix, message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.` }) } dict[key] = value } } return dict } } webidl.nullableConverter = function (converter) { return (V, prefix, argument) => { if (V === null) { return V } return converter(V, prefix, argument) } } /** * @param {*} value * @returns {boolean} */ webidl.is.USVString = function (value) { return ( typeof value === 'string' && value.isWellFormed() ) } webidl.is.ReadableStream = webidl.util.MakeTypeAssertion(ReadableStream) webidl.is.Blob = webidl.util.MakeTypeAssertion(Blob) webidl.is.URLSearchParams = webidl.util.MakeTypeAssertion(URLSearchParams) webidl.is.File = webidl.util.MakeTypeAssertion(File) webidl.is.URL = webidl.util.MakeTypeAssertion(URL) webidl.is.AbortSignal = webidl.util.MakeTypeAssertion(AbortSignal) webidl.is.MessagePort = webidl.util.MakeTypeAssertion(MessagePort) webidl.is.BufferSource = function (V) { return types.isArrayBuffer(V) || ( ArrayBuffer.isView(V) && types.isArrayBuffer(V.buffer) ) } // https://webidl.spec.whatwg.org/#es-DOMString webidl.converters.DOMString = function (V, prefix, argument, flags) { // 1. If V is null and the conversion is to an IDL type // associated with the [LegacyNullToEmptyString] // extended attribute, then return the DOMString value // that represents the empty string. if (V === null && webidl.util.HasFlag(flags, webidl.attributes.LegacyNullToEmptyString)) { return '' } // 2. Let x be ? ToString(V). if (typeof V === 'symbol') { throw webidl.errors.exception({ header: prefix, message: `${argument} is a symbol, which cannot be converted to a DOMString.` }) } // 3. Return the IDL DOMString value that represents the // same sequence of code units as the one the // ECMAScript String value x represents. return String(V) } // https://webidl.spec.whatwg.org/#es-ByteString webidl.converters.ByteString = function (V, prefix, argument) { // 1. Let x be ? ToString(V). if (typeof V === 'symbol') { throw webidl.errors.exception({ header: prefix, message: `${argument} is a symbol, which cannot be converted to a ByteString.` }) } const x = String(V) // 2. If the value of any element of x is greater than // 255, then throw a TypeError. for (let index = 0; index < x.length; index++) { if (x.charCodeAt(index) > 255) { throw new TypeError( 'Cannot convert argument to a ByteString because the character at ' + `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` ) } } // 3. Return an IDL ByteString value whose length is the // length of x, and where the value of each element is // the value of the corresponding element of x. return x } /** * @param {unknown} value * @returns {string} * @see https://webidl.spec.whatwg.org/#es-USVString */ webidl.converters.USVString = function (value) { // TODO: rewrite this so we can control the errors thrown if (typeof value === 'string') { return value.toWellFormed() } return `${value}`.toWellFormed() } // https://webidl.spec.whatwg.org/#es-boolean webidl.converters.boolean = function (V) { // 1. Let x be the result of computing ToBoolean(V). // https://262.ecma-international.org/10.0/index.html#table-10 const x = Boolean(V) // 2. Return the IDL boolean value that is the one that represents // the same truth value as the ECMAScript Boolean value x. return x } // https://webidl.spec.whatwg.org/#es-any webidl.converters.any = function (V) { return V } // https://webidl.spec.whatwg.org/#es-long-long webidl.converters['long long'] = function (V, prefix, argument) { // 1. Let x be ? ConvertToInt(V, 64, "signed"). const x = webidl.util.ConvertToInt(V, 64, 'signed', 0, prefix, argument) // 2. Return the IDL long long value that represents // the same numeric value as x. return x } // https://webidl.spec.whatwg.org/#es-unsigned-long-long webidl.converters['unsigned long long'] = function (V, prefix, argument) { // 1. Let x be ? ConvertToInt(V, 64, "unsigned"). const x = webidl.util.ConvertToInt(V, 64, 'unsigned', 0, prefix, argument) // 2. Return the IDL unsigned long long value that // represents the same numeric value as x. return x } // https://webidl.spec.whatwg.org/#es-unsigned-long webidl.converters['unsigned long'] = function (V, prefix, argument) { // 1. Let x be ? ConvertToInt(V, 32, "unsigned"). const x = webidl.util.ConvertToInt(V, 32, 'unsigned', 0, prefix, argument) // 2. Return the IDL unsigned long value that // represents the same numeric value as x. return x } // https://webidl.spec.whatwg.org/#es-unsigned-short webidl.converters['unsigned short'] = function (V, prefix, argument, flags) { // 1. Let x be ? ConvertToInt(V, 16, "unsigned"). const x = webidl.util.ConvertToInt(V, 16, 'unsigned', flags, prefix, argument) // 2. Return the IDL unsigned short value that represents // the same numeric value as x. return x } // https://webidl.spec.whatwg.org/#idl-ArrayBuffer webidl.converters.ArrayBuffer = function (V, prefix, argument, flags) { // 1. If V is not an Object, or V does not have an // [[ArrayBufferData]] internal slot, then throw a // TypeError. // 2. If IsSharedArrayBuffer(V) is true, then throw a // TypeError. // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances if ( webidl.util.Type(V) !== OBJECT || !types.isArrayBuffer(V) ) { throw webidl.errors.conversionFailed({ prefix, argument: `${argument} ("${webidl.util.Stringify(V)}")`, types: ['ArrayBuffer'] }) } // 3. If the conversion is not to an IDL type associated // with the [AllowResizable] extended attribute, and // IsResizableArrayBuffer(V) is true, then throw a // TypeError. if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V)) { throw webidl.errors.exception({ header: prefix, message: `${argument} cannot be a resizable ArrayBuffer.` }) } // 4. Return the IDL ArrayBuffer value that is a // reference to the same object as V. return V } // https://webidl.spec.whatwg.org/#idl-SharedArrayBuffer webidl.converters.SharedArrayBuffer = function (V, prefix, argument, flags) { // 1. If V is not an Object, or V does not have an // [[ArrayBufferData]] internal slot, then throw a // TypeError. // 2. If IsSharedArrayBuffer(V) is false, then throw a // TypeError. // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances if ( webidl.util.Type(V) !== OBJECT || !types.isSharedArrayBuffer(V) ) { throw webidl.errors.conversionFailed({ prefix, argument: `${argument} ("${webidl.util.Stringify(V)}")`, types: ['SharedArrayBuffer'] }) } // 3. If the conversion is not to an IDL type associated // with the [AllowResizable] extended attribute, and // IsResizableArrayBuffer(V) is true, then throw a // TypeError. if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V)) { throw webidl.errors.exception({ header: prefix, message: `${argument} cannot be a resizable SharedArrayBuffer.` }) } // 4. Return the IDL SharedArrayBuffer value that is a // reference to the same object as V. return V } // https://webidl.spec.whatwg.org/#dfn-typed-array-type webidl.converters.TypedArray = function (V, T, prefix, argument, flags) { // 1. Let T be the IDL type V is being converted to. // 2. If Type(V) is not Object, or V does not have a // [[TypedArrayName]] internal slot with a value // equal to T’s name, then throw a TypeError. if ( webidl.util.Type(V) !== OBJECT || !types.isTypedArray(V) || V.constructor.name !== T.name ) { throw webidl.errors.conversionFailed({ prefix, argument: `${argument} ("${webidl.util.Stringify(V)}")`, types: [T.name] }) } // 3. If the conversion is not to an IDL type associated // with the [AllowShared] extended attribute, and // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is // true, then throw a TypeError. if (!webidl.util.HasFlag(flags, webidl.attributes.AllowShared) && types.isSharedArrayBuffer(V.buffer)) { throw webidl.errors.exception({ header: prefix, message: `${argument} cannot be a view on a shared array buffer.` }) } // 4. If the conversion is not to an IDL type associated // with the [AllowResizable] extended attribute, and // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is // true, then throw a TypeError. if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V.buffer)) { throw webidl.errors.exception({ header: prefix, message: `${argument} cannot be a view on a resizable array buffer.` }) } // 5. Return the IDL value of type T that is a reference // to the same object as V. return V } // https://webidl.spec.whatwg.org/#idl-DataView webidl.converters.DataView = function (V, prefix, argument, flags) { // 1. If Type(V) is not Object, or V does not have a // [[DataView]] internal slot, then throw a TypeError. if (webidl.util.Type(V) !== OBJECT || !types.isDataView(V)) { throw webidl.errors.conversionFailed({ prefix, argument: `${argument} ("${webidl.util.Stringify(V)}")`, types: ['DataView'] }) } // 2. If the conversion is not to an IDL type associated // with the [AllowShared] extended attribute, and // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, // then throw a TypeError. if (!webidl.util.HasFlag(flags, webidl.attributes.AllowShared) && types.isSharedArrayBuffer(V.buffer)) { throw webidl.errors.exception({ header: prefix, message: `${argument} cannot be a view on a shared array buffer.` }) } // 3. If the conversion is not to an IDL type associated // with the [AllowResizable] extended attribute, and // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is // true, then throw a TypeError. if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V.buffer)) { throw webidl.errors.exception({ header: prefix, message: `${argument} cannot be a view on a resizable array buffer.` }) } // 4. Return the IDL DataView value that is a reference // to the same object as V. return V } // https://webidl.spec.whatwg.org/#ArrayBufferView webidl.converters.ArrayBufferView = function (V, prefix, argument, flags) { if ( webidl.util.Type(V) !== OBJECT || !types.isArrayBufferView(V) ) { throw webidl.errors.conversionFailed({ prefix, argument: `${argument} ("${webidl.util.Stringify(V)}")`, types: ['ArrayBufferView'] }) } if (!webidl.util.HasFlag(flags, webidl.attributes.AllowShared) && types.isSharedArrayBuffer(V.buffer)) { throw webidl.errors.exception({ header: prefix, message: `${argument} cannot be a view on a shared array buffer.` }) } if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V.buffer)) { throw webidl.errors.exception({ header: prefix, message: `${argument} cannot be a view on a resizable array buffer.` }) } return V } // https://webidl.spec.whatwg.org/#BufferSource webidl.converters.BufferSource = function (V, prefix, argument, flags) { if (types.isArrayBuffer(V)) { return webidl.converters.ArrayBuffer(V, prefix, argument, flags) } if (types.isArrayBufferView(V)) { flags &= ~webidl.attributes.AllowShared return webidl.converters.ArrayBufferView(V, prefix, argument, flags) } // Make this explicit for easier debugging if (types.isSharedArrayBuffer(V)) { throw webidl.errors.exception({ header: prefix, message: `${argument} cannot be a SharedArrayBuffer.` }) } throw webidl.errors.conversionFailed({ prefix, argument: `${argument} ("${webidl.util.Stringify(V)}")`, types: ['ArrayBuffer', 'ArrayBufferView'] }) } // https://webidl.spec.whatwg.org/#AllowSharedBufferSource webidl.converters.AllowSharedBufferSource = function (V, prefix, argument, flags) { if (types.isArrayBuffer(V)) { return webidl.converters.ArrayBuffer(V, prefix, argument, flags) } if (types.isSharedArrayBuffer(V)) { return webidl.converters.SharedArrayBuffer(V, prefix, argument, flags) } if (types.isArrayBufferView(V)) { flags |= webidl.attributes.AllowShared return webidl.converters.ArrayBufferView(V, prefix, argument, flags) } throw webidl.errors.conversionFailed({ prefix, argument: `${argument} ("${webidl.util.Stringify(V)}")`, types: ['ArrayBuffer', 'SharedArrayBuffer', 'ArrayBufferView'] }) } webidl.converters['sequence<ByteString>'] = webidl.sequenceConverter( webidl.converters.ByteString ) webidl.converters['sequence<sequence<ByteString>>'] = webidl.sequenceConverter( webidl.converters['sequence<ByteString>'] ) webidl.converters['record<ByteString, ByteString>'] = webidl.recordConverter( webidl.converters.ByteString, webidl.converters.ByteString ) webidl.converters.Blob = webidl.interfaceConverter(webidl.is.Blob, 'Blob') webidl.converters.AbortSignal = webidl.interfaceConverter( webidl.is.AbortSignal, 'AbortSignal' ) /** * [LegacyTreatNonObjectAsNull] * callback EventHandlerNonNull = any (Event event); * typedef EventHandlerNonNull? EventHandler; * @param {*} V */ webidl.converters.EventHandlerNonNull = function (V) { if (webidl.util.Type(V) !== OBJECT) { return null } // [I]f the value is not an object, it will be converted to null, and if the value is not callable, // it will be converted to a callback function value that does nothing when called. if (typeof V === 'function') { return V } return () => {} } webidl.attributes = { Clamp: 1 << 0, EnforceRange: 1 << 1, AllowShared: 1 << 2, AllowResizable: 1 << 3, LegacyNullToEmptyString: 1 << 4 } module.exports = { webidl }
最新发布
09-11
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package org.springframework.boot; import java.lang.reflect.Constructor; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanNameGenerator; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.boot.Banner.Mode; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.boot.context.properties.source.ConfigurationPropertySources; import org.springframework.boot.convert.ApplicationConversionService; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.GenericTypeResolver; import org.springframework.core.Ordered; import org.springframework.core.annotation.AnnotationAwareOrderComparator; import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; import org.springframework.core.env.SimpleCommandLinePropertySource; import org.springframework.core.env.StandardEnvironment; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.SpringFactoriesLoader; import org.springframework.core.metrics.ApplicationStartup; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; public class SpringApplication { public static final String BANNER_LOCATION_PROPERTY_VALUE = "banner.txt"; public static final String BANNER_LOCATION_PROPERTY = "spring.banner.location"; private static final String SYSTEM_PROPERTY_JAVA_AWT_HEADLESS = "java.awt.headless"; private static final Log logger = LogFactory.getLog(SpringApplication.class); static final SpringApplicationShutdownHook shutdownHook = new SpringApplicationShutdownHook(); private Set<Class<?>> primarySources; private Set<String> sources; private Class<?> mainApplicationClass; private Banner.Mode bannerMode; private boolean logStartupInfo; private boolean addCommandLineProperties; private boolean addConversionService; private Banner banner; private ResourceLoader resourceLoader; private BeanNameGenerator beanNameGenerator; private ConfigurableEnvironment environment; private WebApplicationType webApplicationType; private boolean headless; private boolean registerShutdownHook; private List<ApplicationContextInitializer<?>> initializers; private List<ApplicationListener<?>> listeners; private Map<String, Object> defaultProperties; private List<BootstrapRegistryInitializer> bootstrapRegistryInitializers; private Set<String> additionalProfiles; private boolean allowBeanDefinitionOverriding; private boolean allowCircularReferences; private boolean isCustomEnvironment; private boolean lazyInitialization; private String environmentPrefix; private ApplicationContextFactory applicationContextFactory; private ApplicationStartup applicationStartup; public SpringApplication(Class<?>... primarySources) { this((ResourceLoader)null, primarySources); } public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) { this.sources = new LinkedHashSet(); this.bannerMode = Mode.CONSOLE; this.logStartupInfo = true; this.addCommandLineProperties = true; this.addConversionService = true; this.headless = true; this.registerShutdownHook = true; this.additionalProfiles = Collections.emptySet(); this.isCustomEnvironment = false; this.lazyInitialization = false; this.applicationContextFactory = ApplicationContextFactory.DEFAULT; this.applicationStartup = ApplicationStartup.DEFAULT; this.resourceLoader = resourceLoader; Assert.notNull(primarySources, "PrimarySources must not be null"); this.primarySources = new LinkedHashSet(Arrays.asList(primarySources)); this.webApplicationType = WebApplicationType.deduceFromClasspath(); this.bootstrapRegistryInitializers = new ArrayList(this.getSpringFactoriesInstances(BootstrapRegistryInitializer.class)); this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class)); this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class)); this.mainApplicationClass = this.deduceMainApplicationClass(); } private Class<?> deduceMainApplicationClass() { try { StackTraceElement[] stackTrace = (new RuntimeException()).getStackTrace(); StackTraceElement[] var2 = stackTrace; int var3 = stackTrace.length; for(int var4 = 0; var4 < var3; ++var4) { StackTraceElement stackTraceElement = var2[var4]; if ("main".equals(stackTraceElement.getMethodName())) { return Class.forName(stackTraceElement.getClassName()); } } } catch (ClassNotFoundException var6) { } return null; } public ConfigurableApplicationContext run(String... args) { long startTime = System.nanoTime(); DefaultBootstrapContext bootstrapContext = this.createBootstrapContext(); ConfigurableApplicationContext context = null; this.configureHeadlessProperty(); SpringApplicationRunListeners listeners = this.getRunListeners(args); listeners.starting(bootstrapContext, this.mainApplicationClass); try { ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); ConfigurableEnvironment environment = this.prepareEnvironment(listeners, bootstrapContext, applicationArguments); this.configureIgnoreBeanInfo(environment); Banner printedBanner = this.printBanner(environment); context = this.createApplicationContext(); context.setApplicationStartup(this.applicationStartup); this.prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner); this.refreshContext(context); this.afterRefresh(context, applicationArguments); Duration timeTakenToStartup = Duration.ofNanos(System.nanoTime() - startTime); if (this.logStartupInfo) { (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), timeTakenToStartup); } listeners.started(context, timeTakenToStartup); this.callRunners(context, applicationArguments); } catch (Throwable var12) { this.handleRunFailure(context, var12, listeners); throw new IllegalStateException(var12); } try { Duration timeTakenToReady = Duration.ofNanos(System.nanoTime() - startTime); listeners.ready(context, timeTakenToReady); return context; } catch (Throwable var11) { this.handleRunFailure(context, var11, (SpringApplicationRunListeners)null); throw new IllegalStateException(var11); } } private DefaultBootstrapContext createBootstrapContext() { DefaultBootstrapContext bootstrapContext = new DefaultBootstrapContext(); this.bootstrapRegistryInitializers.forEach((initializer) -> { initializer.initialize(bootstrapContext); }); return bootstrapContext; } private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners, DefaultBootstrapContext bootstrapContext, ApplicationArguments applicationArguments) { ConfigurableEnvironment environment = this.getOrCreateEnvironment(); this.configureEnvironment((ConfigurableEnvironment)environment, applicationArguments.getSourceArgs()); ConfigurationPropertySources.attach((Environment)environment); listeners.environmentPrepared(bootstrapContext, (ConfigurableEnvironment)environment); DefaultPropertiesPropertySource.moveToEnd((ConfigurableEnvironment)environment); Assert.state(!((ConfigurableEnvironment)environment).containsProperty("spring.main.environment-prefix"), "Environment prefix cannot be set via properties."); this.bindToSpringApplication((ConfigurableEnvironment)environment); if (!this.isCustomEnvironment) { environment = this.convertEnvironment((ConfigurableEnvironment)environment); } ConfigurationPropertySources.attach((Environment)environment); return (ConfigurableEnvironment)environment; } /** @deprecated */ @Deprecated public StandardEnvironment convertEnvironment(ConfigurableEnvironment environment) { return (new EnvironmentConverter(this.getClassLoader())).convertEnvironmentIfNecessary(environment, this.deduceEnvironmentClass()); } private Class<? extends StandardEnvironment> deduceEnvironmentClass() { switch (this.webApplicationType) { case SERVLET: return ApplicationServletEnvironment.class; case REACTIVE: return ApplicationReactiveWebEnvironment.class; default: return ApplicationEnvironment.class; } } private void prepareContext(DefaultBootstrapContext bootstrapContext, ConfigurableApplicationContext context, ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) { context.setEnvironment(environment); this.postProcessApplicationContext(context); this.applyInitializers(context); listeners.contextPrepared(context); bootstrapContext.close(context); if (this.logStartupInfo) { this.logStartupInfo(context.getParent() == null); this.logStartupProfileInfo(context); } ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); beanFactory.registerSingleton("springApplicationArguments", applicationArguments); if (printedBanner != null) { beanFactory.registerSingleton("springBootBanner", printedBanner); } if (beanFactory instanceof AbstractAutowireCapableBeanFactory) { ((AbstractAutowireCapableBeanFactory)beanFactory).setAllowCircularReferences(this.allowCircularReferences); if (beanFactory instanceof DefaultListableBeanFactory) { ((DefaultListableBeanFactory)beanFactory).setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding); } } if (this.lazyInitialization) { context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor()); } context.addBeanFactoryPostProcessor(new PropertySourceOrderingBeanFactoryPostProcessor(context)); Set<Object> sources = this.getAllSources(); Assert.notEmpty(sources, "Sources must not be empty"); this.load(context, sources.toArray(new Object[0])); listeners.contextLoaded(context); } private void refreshContext(ConfigurableApplicationContext context) { if (this.registerShutdownHook) { shutdownHook.registerApplicationContext(context); } this.refresh(context); } private void configureHeadlessProperty() { System.setProperty("java.awt.headless", System.getProperty("java.awt.headless", Boolean.toString(this.headless))); } private SpringApplicationRunListeners getRunListeners(String[] args) { Class<?>[] types = new Class[]{SpringApplication.class, String[].class}; return new SpringApplicationRunListeners(logger, this.getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args), this.applicationStartup); } private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) { return this.getSpringFactoriesInstances(type, new Class[0]); } private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) { ClassLoader classLoader = this.getClassLoader(); Set<String> names = new LinkedHashSet(SpringFactoriesLoader.loadFactoryNames(type, classLoader)); List<T> instances = this.createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names); AnnotationAwareOrderComparator.sort(instances); return instances; } private <T> List<T> createSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, ClassLoader classLoader, Object[] args, Set<String> names) { List<T> instances = new ArrayList(names.size()); Iterator var7 = names.iterator(); while(var7.hasNext()) { String name = (String)var7.next(); try { Class<?> instanceClass = ClassUtils.forName(name, classLoader); Assert.isAssignable(type, instanceClass); Constructor<?> constructor = instanceClass.getDeclaredConstructor(parameterTypes); T instance = BeanUtils.instantiateClass(constructor, args); instances.add(instance); } catch (Throwable var12) { throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, var12); } } return instances; } private ConfigurableEnvironment getOrCreateEnvironment() { if (this.environment != null) { return this.environment; } else { switch (this.webApplicationType) { case SERVLET: return new ApplicationServletEnvironment(); case REACTIVE: return new ApplicationReactiveWebEnvironment(); default: return new ApplicationEnvironment(); } } } protected void configureEnvironment(ConfigurableEnvironment environment, String[] args) { if (this.addConversionService) { environment.setConversionService(new ApplicationConversionService()); } this.configurePropertySources(environment, args); this.configureProfiles(environment, args); } protected void configurePropertySources(ConfigurableEnvironment environment, String[] args) { MutablePropertySources sources = environment.getPropertySources(); if (!CollectionUtils.isEmpty(this.defaultProperties)) { DefaultPropertiesPropertySource.addOrMerge(this.defaultProperties, sources); } if (this.addCommandLineProperties && args.length > 0) { String name = "commandLineArgs"; if (sources.contains(name)) { PropertySource<?> source = sources.get(name); CompositePropertySource composite = new CompositePropertySource(name); composite.addPropertySource(new SimpleCommandLinePropertySource("springApplicationCommandLineArgs", args)); composite.addPropertySource(source); sources.replace(name, composite); } else { sources.addFirst(new SimpleCommandLinePropertySource(args)); } } } protected void configureProfiles(ConfigurableEnvironment environment, String[] args) { } private void configureIgnoreBeanInfo(ConfigurableEnvironment environment) { if (System.getProperty("spring.beaninfo.ignore") == null) { Boolean ignore = (Boolean)environment.getProperty("spring.beaninfo.ignore", Boolean.class, Boolean.TRUE); System.setProperty("spring.beaninfo.ignore", ignore.toString()); } } protected void bindToSpringApplication(ConfigurableEnvironment environment) { try { Binder.get(environment).bind("spring.main", Bindable.ofInstance(this)); } catch (Exception var3) { throw new IllegalStateException("Cannot bind to SpringApplication", var3); } } private Banner printBanner(ConfigurableEnvironment environment) { if (this.bannerMode == Mode.OFF) { return null; } else { ResourceLoader resourceLoader = this.resourceLoader != null ? this.resourceLoader : new DefaultResourceLoader((ClassLoader)null); SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter((ResourceLoader)resourceLoader, this.banner); return this.bannerMode == Mode.LOG ? bannerPrinter.print(environment, this.mainApplicationClass, logger) : bannerPrinter.print(environment, this.mainApplicationClass, System.out); } } protected ConfigurableApplicationContext createApplicationContext() { return this.applicationContextFactory.create(this.webApplicationType); } protected void postProcessApplicationContext(ConfigurableApplicationContext context) { if (this.beanNameGenerator != null) { context.getBeanFactory().registerSingleton("org.springframework.context.annotation.internalConfigurationBeanNameGenerator", this.beanNameGenerator); } if (this.resourceLoader != null) { if (context instanceof GenericApplicationContext) { ((GenericApplicationContext)context).setResourceLoader(this.resourceLoader); } if (context instanceof DefaultResourceLoader) { ((DefaultResourceLoader)context).setClassLoader(this.resourceLoader.getClassLoader()); } } if (this.addConversionService) { context.getBeanFactory().setConversionService(context.getEnvironment().getConversionService()); } } protected void applyInitializers(ConfigurableApplicationContext context) { Iterator var2 = this.getInitializers().iterator(); while(var2.hasNext()) { ApplicationContextInitializer initializer = (ApplicationContextInitializer)var2.next(); Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(), ApplicationContextInitializer.class); Assert.isInstanceOf(requiredType, context, "Unable to call initializer."); initializer.initialize(context); } } protected void logStartupInfo(boolean isRoot) { if (isRoot) { (new StartupInfoLogger(this.mainApplicationClass)).logStarting(this.getApplicationLog()); } } protected void logStartupProfileInfo(ConfigurableApplicationContext context) { Log log = this.getApplicationLog(); if (log.isInfoEnabled()) { List<String> activeProfiles = this.quoteProfiles(context.getEnvironment().getActiveProfiles()); if (ObjectUtils.isEmpty(activeProfiles)) { List<String> defaultProfiles = this.quoteProfiles(context.getEnvironment().getDefaultProfiles()); String message = String.format("%s default %s: ", defaultProfiles.size(), defaultProfiles.size() <= 1 ? "profile" : "profiles"); log.info("No active profile set, falling back to " + message + StringUtils.collectionToDelimitedString(defaultProfiles, ", ")); } else { String message = activeProfiles.size() == 1 ? "1 profile is active: " : activeProfiles.size() + " profiles are active: "; log.info("The following " + message + StringUtils.collectionToDelimitedString(activeProfiles, ", ")); } } } private List<String> quoteProfiles(String[] profiles) { return (List)Arrays.stream(profiles).map((profile) -> { return "\"" + profile + "\""; }).collect(Collectors.toList()); } protected Log getApplicationLog() { return this.mainApplicationClass == null ? logger : LogFactory.getLog(this.mainApplicationClass); } protected void load(ApplicationContext context, Object[] sources) { if (logger.isDebugEnabled()) { logger.debug("Loading source " + StringUtils.arrayToCommaDelimitedString(sources)); } BeanDefinitionLoader loader = this.createBeanDefinitionLoader(this.getBeanDefinitionRegistry(context), sources); if (this.beanNameGenerator != null) { loader.setBeanNameGenerator(this.beanNameGenerator); } if (this.resourceLoader != null) { loader.setResourceLoader(this.resourceLoader); } if (this.environment != null) { loader.setEnvironment(this.environment); } loader.load(); } public ResourceLoader getResourceLoader() { return this.resourceLoader; } public ClassLoader getClassLoader() { return this.resourceLoader != null ? this.resourceLoader.getClassLoader() : ClassUtils.getDefaultClassLoader(); } private BeanDefinitionRegistry getBeanDefinitionRegistry(ApplicationContext context) { if (context instanceof BeanDefinitionRegistry) { return (BeanDefinitionRegistry)context; } else if (context instanceof AbstractApplicationContext) { return (BeanDefinitionRegistry)((AbstractApplicationContext)context).getBeanFactory(); } else { throw new IllegalStateException("Could not locate BeanDefinitionRegistry"); } } protected BeanDefinitionLoader createBeanDefinitionLoader(BeanDefinitionRegistry registry, Object[] sources) { return new BeanDefinitionLoader(registry, sources); } protected void refresh(ConfigurableApplicationContext applicationContext) { applicationContext.refresh(); } protected void afterRefresh(ConfigurableApplicationContext context, ApplicationArguments args) { } private void callRunners(ApplicationContext context, ApplicationArguments args) { List<Object> runners = new ArrayList(); runners.addAll(context.getBeansOfType(ApplicationRunner.class).values()); runners.addAll(context.getBeansOfType(CommandLineRunner.class).values()); AnnotationAwareOrderComparator.sort(runners); Iterator var4 = (new LinkedHashSet(runners)).iterator(); while(var4.hasNext()) { Object runner = var4.next(); if (runner instanceof ApplicationRunner) { this.callRunner((ApplicationRunner)runner, args); } if (runner instanceof CommandLineRunner) { this.callRunner((CommandLineRunner)runner, args); } } } private void callRunner(ApplicationRunner runner, ApplicationArguments args) { try { runner.run(args); } catch (Exception var4) { throw new IllegalStateException("Failed to execute ApplicationRunner", var4); } } private void callRunner(CommandLineRunner runner, ApplicationArguments args) { try { runner.run(args.getSourceArgs()); } catch (Exception var4) { throw new IllegalStateException("Failed to execute CommandLineRunner", var4); } } private void handleRunFailure(ConfigurableApplicationContext context, Throwable exception, SpringApplicationRunListeners listeners) { try { try { this.handleExitCode(context, exception); if (listeners != null) { listeners.failed(context, exception); } } finally { this.reportFailure(this.getExceptionReporters(context), exception); if (context != null) { context.close(); shutdownHook.deregisterFailedApplicationContext(context); } } } catch (Exception var8) { logger.warn("Unable to close ApplicationContext", var8); } ReflectionUtils.rethrowRuntimeException(exception); } private Collection<SpringBootExceptionReporter> getExceptionReporters(ConfigurableApplicationContext context) { try { return this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context); } catch (Throwable var3) { return Collections.emptyList(); } } private void reportFailure(Collection<SpringBootExceptionReporter> exceptionReporters, Throwable failure) { try { Iterator var3 = exceptionReporters.iterator(); while(var3.hasNext()) { SpringBootExceptionReporter reporter = (SpringBootExceptionReporter)var3.next(); if (reporter.reportException(failure)) { this.registerLoggedException(failure); return; } } } catch (Throwable var5) { } if (logger.isErrorEnabled()) { logger.error("Application run failed", failure); this.registerLoggedException(failure); } } protected void registerLoggedException(Throwable exception) { SpringBootExceptionHandler handler = this.getSpringBootExceptionHandler(); if (handler != null) { handler.registerLoggedException(exception); } } private void handleExitCode(ConfigurableApplicationContext context, Throwable exception) { int exitCode = this.getExitCodeFromException(context, exception); if (exitCode != 0) { if (context != null) { context.publishEvent(new ExitCodeEvent(context, exitCode)); } SpringBootExceptionHandler handler = this.getSpringBootExceptionHandler(); if (handler != null) { handler.registerExitCode(exitCode); } } } private int getExitCodeFromException(ConfigurableApplicationContext context, Throwable exception) { int exitCode = this.getExitCodeFromMappedException(context, exception); if (exitCode == 0) { exitCode = this.getExitCodeFromExitCodeGeneratorException(exception); } return exitCode; } private int getExitCodeFromMappedException(ConfigurableApplicationContext context, Throwable exception) { if (context != null && context.isActive()) { ExitCodeGenerators generators = new ExitCodeGenerators(); Collection<ExitCodeExceptionMapper> beans = context.getBeansOfType(ExitCodeExceptionMapper.class).values(); generators.addAll(exception, beans); return generators.getExitCode(); } else { return 0; } } private int getExitCodeFromExitCodeGeneratorException(Throwable exception) { if (exception == null) { return 0; } else { return exception instanceof ExitCodeGenerator ? ((ExitCodeGenerator)exception).getExitCode() : this.getExitCodeFromExitCodeGeneratorException(exception.getCause()); } } SpringBootExceptionHandler getSpringBootExceptionHandler() { return this.isMainThread(Thread.currentThread()) ? SpringBootExceptionHandler.forCurrentThread() : null; } private boolean isMainThread(Thread currentThread) { return ("main".equals(currentThread.getName()) || "restartedMain".equals(currentThread.getName())) && "main".equals(currentThread.getThreadGroup().getName()); } public Class<?> getMainApplicationClass() { return this.mainApplicationClass; } public void setMainApplicationClass(Class<?> mainApplicationClass) { this.mainApplicationClass = mainApplicationClass; } public WebApplicationType getWebApplicationType() { return this.webApplicationType; } public void setWebApplicationType(WebApplicationType webApplicationType) { Assert.notNull(webApplicationType, "WebApplicationType must not be null"); this.webApplicationType = webApplicationType; } public void setAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding) { this.allowBeanDefinitionOverriding = allowBeanDefinitionOverriding; } public void setAllowCircularReferences(boolean allowCircularReferences) { this.allowCircularReferences = allowCircularReferences; } public void setLazyInitialization(boolean lazyInitialization) { this.lazyInitialization = lazyInitialization; } public void setHeadless(boolean headless) { this.headless = headless; } public void setRegisterShutdownHook(boolean registerShutdownHook) { this.registerShutdownHook = registerShutdownHook; } public void setBanner(Banner banner) { this.banner = banner; } public void setBannerMode(Banner.Mode bannerMode) { this.bannerMode = bannerMode; } public void setLogStartupInfo(boolean logStartupInfo) { this.logStartupInfo = logStartupInfo; } public void setAddCommandLineProperties(boolean addCommandLineProperties) { this.addCommandLineProperties = addCommandLineProperties; } public void setAddConversionService(boolean addConversionService) { this.addConversionService = addConversionService; } public void addBootstrapRegistryInitializer(BootstrapRegistryInitializer bootstrapRegistryInitializer) { Assert.notNull(bootstrapRegistryInitializer, "BootstrapRegistryInitializer must not be null"); this.bootstrapRegistryInitializers.addAll(Arrays.asList(bootstrapRegistryInitializer)); } public void setDefaultProperties(Map<String, Object> defaultProperties) { this.defaultProperties = defaultProperties; } public void setDefaultProperties(Properties defaultProperties) { this.defaultProperties = new HashMap(); Iterator var2 = Collections.list(defaultProperties.propertyNames()).iterator(); while(var2.hasNext()) { Object key = var2.next(); this.defaultProperties.put((String)key, defaultProperties.get(key)); } } public void setAdditionalProfiles(String... profiles) { this.additionalProfiles = Collections.unmodifiableSet(new LinkedHashSet(Arrays.asList(profiles))); } public Set<String> getAdditionalProfiles() { return this.additionalProfiles; } public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) { this.beanNameGenerator = beanNameGenerator; } public void setEnvironment(ConfigurableEnvironment environment) { this.isCustomEnvironment = true; this.environment = environment; } public void addPrimarySources(Collection<Class<?>> additionalPrimarySources) { this.primarySources.addAll(additionalPrimarySources); } public Set<String> getSources() { return this.sources; } public void setSources(Set<String> sources) { Assert.notNull(sources, "Sources must not be null"); this.sources = new LinkedHashSet(sources); } public Set<Object> getAllSources() { Set<Object> allSources = new LinkedHashSet(); if (!CollectionUtils.isEmpty(this.primarySources)) { allSources.addAll(this.primarySources); } if (!CollectionUtils.isEmpty(this.sources)) { allSources.addAll(this.sources); } return Collections.unmodifiableSet(allSources); } public void setResourceLoader(ResourceLoader resourceLoader) { Assert.notNull(resourceLoader, "ResourceLoader must not be null"); this.resourceLoader = resourceLoader; } public String getEnvironmentPrefix() { return this.environmentPrefix; } public void setEnvironmentPrefix(String environmentPrefix) { this.environmentPrefix = environmentPrefix; } public void setApplicationContextFactory(ApplicationContextFactory applicationContextFactory) { this.applicationContextFactory = applicationContextFactory != null ? applicationContextFactory : ApplicationContextFactory.DEFAULT; } public void setInitializers(Collection<? extends ApplicationContextInitializer<?>> initializers) { this.initializers = new ArrayList(initializers); } public void addInitializers(ApplicationContextInitializer<?>... initializers) { this.initializers.addAll(Arrays.asList(initializers)); } public Set<ApplicationContextInitializer<?>> getInitializers() { return asUnmodifiableOrderedSet(this.initializers); } public void setListeners(Collection<? extends ApplicationListener<?>> listeners) { this.listeners = new ArrayList(listeners); } public void addListeners(ApplicationListener<?>... listeners) { this.listeners.addAll(Arrays.asList(listeners)); } public Set<ApplicationListener<?>> getListeners() { return asUnmodifiableOrderedSet(this.listeners); } public void setApplicationStartup(ApplicationStartup applicationStartup) { this.applicationStartup = applicationStartup != null ? applicationStartup : ApplicationStartup.DEFAULT; } public ApplicationStartup getApplicationStartup() { return this.applicationStartup; } public static SpringApplicationShutdownHandlers getShutdownHandlers() { return shutdownHook.getHandlers(); } public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) { return run(new Class[]{primarySource}, args); } public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) { return (new SpringApplication(primarySources)).run(args); } public static void main(String[] args) throws Exception { run(new Class[0], args); } public static int exit(ApplicationContext context, ExitCodeGenerator... exitCodeGenerators) { Assert.notNull(context, "Context must not be null"); int exitCode = 0; try { try { ExitCodeGenerators generators = new ExitCodeGenerators(); Collection<ExitCodeGenerator> beans = context.getBeansOfType(ExitCodeGenerator.class).values(); generators.addAll(exitCodeGenerators); generators.addAll(beans); exitCode = generators.getExitCode(); if (exitCode != 0) { context.publishEvent(new ExitCodeEvent(context, exitCode)); } } finally { close(context); } } catch (Exception var9) { var9.printStackTrace(); exitCode = exitCode != 0 ? exitCode : 1; } return exitCode; } private static void close(ApplicationContext context) { if (context instanceof ConfigurableApplicationContext) { ConfigurableApplicationContext closable = (ConfigurableApplicationContext)context; closable.close(); } } private static <E> Set<E> asUnmodifiableOrderedSet(Collection<E> elements) { List<E> list = new ArrayList(elements); list.sort(AnnotationAwareOrderComparator.INSTANCE); return new LinkedHashSet(list); } private static class PropertySourceOrderingBeanFactoryPostProcessor implements BeanFactoryPostProcessor, Ordered { private final ConfigurableApplicationContext context; PropertySourceOrderingBeanFactoryPostProcessor(ConfigurableApplicationContext context) { this.context = context; } public int getOrder() { return Integer.MIN_VALUE; } public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { DefaultPropertiesPropertySource.moveToEnd(this.context.getEnvironment()); } } } 这里面哪一段代码是加载application.yml中的参数的
09-09
/* * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.scheduling.quartz; import java.io.IOException; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import javax.sql.DataSource; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SchedulerFactory; import org.quartz.impl.RemoteScheduler; import org.quartz.impl.SchedulerRepository; import org.quartz.impl.StdSchedulerFactory; import org.quartz.simpl.SimpleThreadPool; import org.quartz.spi.JobFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.SmartLifecycle; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PropertiesLoaderUtils; import org.springframework.lang.Nullable; import org.springframework.scheduling.SchedulingException; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; /** * {@link FactoryBean} that creates and configures a Quartz {@link org.quartz.Scheduler}, * manages its lifecycle as part of the Spring application context, and exposes the * Scheduler as bean reference for dependency injection. * * <p>Allows registration of JobDetails, Calendars and Triggers, automatically * starting the scheduler on initialization and shutting it down on destruction. * In scenarios that just require static registration of jobs at startup, there * is no need to access the Scheduler instance itself in application code. * * <p>For dynamic registration of jobs at runtime, use a bean reference to * this SchedulerFactoryBean to get direct access to the Quartz Scheduler * ({@code org.quartz.Scheduler}). This allows you to create new jobs * and triggers, and also to control and monitor the entire Scheduler. * * <p>Note that Quartz instantiates a new Job for each execution, in * contrast to Timer which uses a TimerTask instance that is shared * between repeated executions. Just JobDetail descriptors are shared. * * <p>When using persistent jobs, it is strongly recommended to perform all * operations on the Scheduler within Spring-managed (or plain JTA) transactions. * Else, database locking will not properly work and might even break. * (See {@link #setDataSource setDataSource} javadoc for details.) * * <p>The preferred way to achieve transactional execution is to demarcate * declarative transactions at the business facade level, which will * automatically apply to Scheduler operations performed within those scopes. * Alternatively, you may add transactional advice for the Scheduler itself. * * <p>Compatible with Quartz 2.1.4 and higher, as of Spring 4.1. * * @author Juergen Hoeller * @since 18.02.2004 * @see #setDataSource * @see org.quartz.Scheduler * @see org.quartz.SchedulerFactory * @see org.quartz.impl.StdSchedulerFactory * @see org.springframework.transaction.interceptor.TransactionProxyFactoryBean */ public class SchedulerFactoryBean extends SchedulerAccessor implements FactoryBean<Scheduler>, BeanNameAware, ApplicationContextAware, InitializingBean, DisposableBean, SmartLifecycle { /** * The thread count property. */ public static final String PROP_THREAD_COUNT = "org.quartz.threadPool.threadCount"; /** * The default thread count. */ public static final int DEFAULT_THREAD_COUNT = 10; private static final ThreadLocal<ResourceLoader> configTimeResourceLoaderHolder = new ThreadLocal<>(); private static final ThreadLocal<Executor> configTimeTaskExecutorHolder = new ThreadLocal<>(); private static final ThreadLocal<DataSource> configTimeDataSourceHolder = new ThreadLocal<>(); private static final ThreadLocal<DataSource> configTimeNonTransactionalDataSourceHolder = new ThreadLocal<>(); /** * Return the {@link ResourceLoader} for the currently configured Quartz Scheduler, * to be used by {@link ResourceLoaderClassLoadHelper}. * <p>This instance will be set before initialization of the corresponding Scheduler, * and reset immediately afterwards. It is thus only available during configuration. * @see #setApplicationContext * @see ResourceLoaderClassLoadHelper */ @Nullable public static ResourceLoader getConfigTimeResourceLoader() { return configTimeResourceLoaderHolder.get(); } /** * Return the {@link Executor} for the currently configured Quartz Scheduler, * to be used by {@link LocalTaskExecutorThreadPool}. * <p>This instance will be set before initialization of the corresponding Scheduler, * and reset immediately afterwards. It is thus only available during configuration. * @since 2.0 * @see #setTaskExecutor * @see LocalTaskExecutorThreadPool */ @Nullable public static Executor getConfigTimeTaskExecutor() { return configTimeTaskExecutorHolder.get(); } /** * Return the {@link DataSource} for the currently configured Quartz Scheduler, * to be used by {@link LocalDataSourceJobStore}. * <p>This instance will be set before initialization of the corresponding Scheduler, * and reset immediately afterwards. It is thus only available during configuration. * @since 1.1 * @see #setDataSource * @see LocalDataSourceJobStore */ @Nullable public static DataSource getConfigTimeDataSource() { return configTimeDataSourceHolder.get(); } /** * Return the non-transactional {@link DataSource} for the currently configured * Quartz Scheduler, to be used by {@link LocalDataSourceJobStore}. * <p>This instance will be set before initialization of the corresponding Scheduler, * and reset immediately afterwards. It is thus only available during configuration. * @since 1.1 * @see #setNonTransactionalDataSource * @see LocalDataSourceJobStore */ @Nullable public static DataSource getConfigTimeNonTransactionalDataSource() { return configTimeNonTransactionalDataSourceHolder.get(); } @Nullable private SchedulerFactory schedulerFactory; private Class<? extends SchedulerFactory> schedulerFactoryClass = StdSchedulerFactory.class; @Nullable private String schedulerName; @Nullable private Resource configLocation; @Nullable private Properties quartzProperties; @Nullable private Executor taskExecutor; @Nullable private DataSource dataSource; @Nullable private DataSource nonTransactionalDataSource; @Nullable private Map<String, ?> schedulerContextMap; @Nullable private String applicationContextSchedulerContextKey; @Nullable private JobFactory jobFactory; private boolean jobFactorySet = false; private boolean autoStartup = true; private int startupDelay = 0; private int phase = DEFAULT_PHASE; private boolean exposeSchedulerInRepository = false; private boolean waitForJobsToCompleteOnShutdown = false; @Nullable private String beanName; @Nullable private ApplicationContext applicationContext; @Nullable private Scheduler scheduler; /** * Set an external Quartz {@link SchedulerFactory} instance to use. * <p>Default is an internal {@link StdSchedulerFactory} instance. If this method is * called, it overrides any class specified through {@link #setSchedulerFactoryClass} * as well as any settings specified through {@link #setConfigLocation}, * {@link #setQuartzProperties}, {@link #setTaskExecutor} or {@link #setDataSource}. * <p><b>NOTE:</b> With an externally provided {@code SchedulerFactory} instance, * local settings such as {@link #setConfigLocation} or {@link #setQuartzProperties} * will be ignored here in {@code SchedulerFactoryBean}, expecting the external * {@code SchedulerFactory} instance to get initialized on its own. * @since 4.3.15 * @see #setSchedulerFactoryClass */ public void setSchedulerFactory(SchedulerFactory schedulerFactory) { this.schedulerFactory = schedulerFactory; } /** * Set the Quartz {@link SchedulerFactory} implementation to use. * <p>Default is the {@link StdSchedulerFactory} class, reading in the standard * {@code quartz.properties} from {@code quartz.jar}. For applying custom Quartz * properties, specify {@link #setConfigLocation "configLocation"} and/or * {@link #setQuartzProperties "quartzProperties"} etc on this local * {@code SchedulerFactoryBean} instance. * @see org.quartz.impl.StdSchedulerFactory * @see #setConfigLocation * @see #setQuartzProperties * @see #setTaskExecutor * @see #setDataSource */ public void setSchedulerFactoryClass(Class<? extends SchedulerFactory> schedulerFactoryClass) { this.schedulerFactoryClass = schedulerFactoryClass; } /** * Set the name of the Scheduler to create via the SchedulerFactory, as an * alternative to the {@code org.quartz.scheduler.instanceName} property. * <p>If not specified, the name will be taken from Quartz properties * ({@code org.quartz.scheduler.instanceName}), or from the declared * {@code SchedulerFactoryBean} bean name as a fallback. * @see #setBeanName * @see StdSchedulerFactory#PROP_SCHED_INSTANCE_NAME * @see org.quartz.SchedulerFactory#getScheduler() * @see org.quartz.SchedulerFactory#getScheduler(String) */ public void setSchedulerName(String schedulerName) { this.schedulerName = schedulerName; } /** * Set the location of the Quartz properties config file, for example * as classpath resource "classpath:quartz.properties". * <p>Note: Can be omitted when all necessary properties are specified * locally via this bean, or when relying on Quartz' default configuration. * @see #setQuartzProperties */ public void setConfigLocation(Resource configLocation) { this.configLocation = configLocation; } /** * Set Quartz properties, like "org.quartz.threadPool.class". * <p>Can be used to override values in a Quartz properties config file, * or to specify all necessary properties locally. * @see #setConfigLocation */ public void setQuartzProperties(Properties quartzProperties) { this.quartzProperties = quartzProperties; } /** * Set a Spring-managed {@link Executor} to use as Quartz backend. * Exposed as thread pool through the Quartz SPI. * <p>Can be used to assign a local JDK ThreadPoolExecutor or a CommonJ * WorkManager as Quartz backend, to avoid Quartz's manual thread creation. * <p>By default, a Quartz SimpleThreadPool will be used, configured through * the corresponding Quartz properties. * @since 2.0 * @see #setQuartzProperties * @see LocalTaskExecutorThreadPool * @see org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor * @see org.springframework.scheduling.concurrent.DefaultManagedTaskExecutor */ public void setTaskExecutor(Executor taskExecutor) { this.taskExecutor = taskExecutor; } /** * Set the default {@link DataSource} to be used by the Scheduler. * <p>Note: If this is set, the Quartz settings should not define * a job store "dataSource" to avoid meaningless double configuration. * Also, do not define a "org.quartz.jobStore.class" property at all. * (You may explicitly define Spring's {@link LocalDataSourceJobStore} * but that's the default when using this method anyway.) * <p>A Spring-specific subclass of Quartz' JobStoreCMT will be used. * It is therefore strongly recommended to perform all operations on * the Scheduler within Spring-managed (or plain JTA) transactions. * Else, database locking will not properly work and might even break * (for example, if trying to obtain a lock on Oracle without a transaction). * <p>Supports both transactional and non-transactional DataSource access. * With a non-XA DataSource and local Spring transactions, a single DataSource * argument is sufficient. In case of an XA DataSource and global JTA transactions, * SchedulerFactoryBean's "nonTransactionalDataSource" property should be set, * passing in a non-XA DataSource that will not participate in global transactions. * @since 1.1 * @see #setNonTransactionalDataSource * @see #setQuartzProperties * @see #setTransactionManager * @see LocalDataSourceJobStore */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } /** * Set the {@link DataSource} to be used <i>for non-transactional access</i>. * <p>This is only necessary if the default DataSource is an XA DataSource that will * always participate in transactions: A non-XA version of that DataSource should * be specified as "nonTransactionalDataSource" in such a scenario. * <p>This is not relevant with a local DataSource instance and Spring transactions. * Specifying a single default DataSource as "dataSource" is sufficient there. * @since 1.1 * @see #setDataSource * @see LocalDataSourceJobStore */ public void setNonTransactionalDataSource(DataSource nonTransactionalDataSource) { this.nonTransactionalDataSource = nonTransactionalDataSource; } /** * Register objects in the Scheduler context via a given Map. * These objects will be available to any Job that runs in this Scheduler. * <p>Note: When using persistent Jobs whose JobDetail will be kept in the * database, do not put Spring-managed beans or an ApplicationContext * reference into the JobDataMap but rather into the SchedulerContext. * @param schedulerContextAsMap a Map with String keys and any objects as * values (for example Spring-managed beans) * @see JobDetailFactoryBean#setJobDataAsMap */ public void setSchedulerContextAsMap(Map<String, ?> schedulerContextAsMap) { this.schedulerContextMap = schedulerContextAsMap; } /** * Set the key of an {@link ApplicationContext} reference to expose in the * SchedulerContext, for example "applicationContext". Default is none. * Only applicable when running in a Spring ApplicationContext. * <p>Note: When using persistent Jobs whose JobDetail will be kept in the * database, do not put an ApplicationContext reference into the JobDataMap * but rather into the SchedulerContext. * <p>In case of a QuartzJobBean, the reference will be applied to the Job * instance as bean property. An "applicationContext" attribute will * correspond to a "setApplicationContext" method in that scenario. * <p>Note that BeanFactory callback interfaces like ApplicationContextAware * are not automatically applied to Quartz Job instances, because Quartz * itself is responsible for the lifecycle of its Jobs. * @see JobDetailFactoryBean#setApplicationContextJobDataKey * @see org.springframework.context.ApplicationContext */ public void setApplicationContextSchedulerContextKey(String applicationContextSchedulerContextKey) { this.applicationContextSchedulerContextKey = applicationContextSchedulerContextKey; } /** * Set the Quartz {@link JobFactory} to use for this Scheduler. * <p>Default is Spring's {@link AdaptableJobFactory}, which supports * {@link java.lang.Runnable} objects as well as standard Quartz * {@link org.quartz.Job} instances. Note that this default only applies * to a <i>local</i> Scheduler, not to a RemoteScheduler (where setting * a custom JobFactory is not supported by Quartz). * <p>Specify an instance of Spring's {@link SpringBeanJobFactory} here * (typically as an inner bean definition) to automatically populate a job's * bean properties from the specified job data map and scheduler context. * @since 2.0 * @see AdaptableJobFactory * @see SpringBeanJobFactory */ public void setJobFactory(JobFactory jobFactory) { this.jobFactory = jobFactory; this.jobFactorySet = true; } /** * Set whether to automatically start the scheduler after initialization. * <p>Default is "true"; set this to "false" to allow for manual startup. */ public void setAutoStartup(boolean autoStartup) { this.autoStartup = autoStartup; } /** * Return whether this scheduler is configured for auto-startup. If "true", * the scheduler will start after the context is refreshed and after the * start delay, if any. */ @Override public boolean isAutoStartup() { return this.autoStartup; } /** * Specify the phase in which this scheduler should be started and stopped. * The startup order proceeds from lowest to highest, and the shutdown order * is the reverse of that. By default this value is {@code Integer.MAX_VALUE} * meaning that this scheduler starts as late as possible and stops as soon * as possible. * @since 3.0 */ public void setPhase(int phase) { this.phase = phase; } /** * Return the phase in which this scheduler will be started and stopped. */ @Override public int getPhase() { return this.phase; } /** * Set the number of seconds to wait after initialization before * starting the scheduler asynchronously. Default is 0, meaning * immediate synchronous startup on initialization of this bean. * <p>Setting this to 10 or 20 seconds makes sense if no jobs * should be run before the entire application has started up. */ public void setStartupDelay(int startupDelay) { this.startupDelay = startupDelay; } /** * Set whether to expose the Spring-managed {@link Scheduler} instance in the * Quartz {@link SchedulerRepository}. Default is "false", since the Spring-managed * Scheduler is usually exclusively intended for access within the Spring context. * <p>Switch this flag to "true" in order to expose the Scheduler globally. * This is not recommended unless you have an existing Spring application that * relies on this behavior. Note that such global exposure was the accidental * default in earlier Spring versions; this has been fixed as of Spring 2.5.6. */ public void setExposeSchedulerInRepository(boolean exposeSchedulerInRepository) { this.exposeSchedulerInRepository = exposeSchedulerInRepository; } /** * Set whether to wait for running jobs to complete on shutdown. * <p>Default is "false". Switch this to "true" if you prefer * fully completed jobs at the expense of a longer shutdown phase. * @see org.quartz.Scheduler#shutdown(boolean) */ public void setWaitForJobsToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown) { this.waitForJobsToCompleteOnShutdown = waitForJobsToCompleteOnShutdown; } @Override public void setBeanName(String name) { this.beanName = name; } @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } //--------------------------------------------------------------------- // Implementation of InitializingBean interface //--------------------------------------------------------------------- @Override public void afterPropertiesSet() throws Exception { if (this.dataSource == null && this.nonTransactionalDataSource != null) { this.dataSource = this.nonTransactionalDataSource; } if (this.applicationContext != null && this.resourceLoader == null) { this.resourceLoader = this.applicationContext; } // Initialize the Scheduler instance... this.scheduler = prepareScheduler(prepareSchedulerFactory()); try { registerListeners(); registerJobsAndTriggers(); } catch (Exception ex) { try { this.scheduler.shutdown(true); } catch (Exception ex2) { logger.debug("Scheduler shutdown exception after registration failure", ex2); } throw ex; } } /** * Create a SchedulerFactory if necessary and apply locally defined Quartz properties to it. * @return the initialized SchedulerFactory */ private SchedulerFactory prepareSchedulerFactory() throws SchedulerException, IOException { SchedulerFactory schedulerFactory = this.schedulerFactory; if (schedulerFactory == null) { // Create local SchedulerFactory instance (typically a StdSchedulerFactory) schedulerFactory = BeanUtils.instantiateClass(this.schedulerFactoryClass); if (schedulerFactory instanceof StdSchedulerFactory stdSchedulerFactory) { initSchedulerFactory(stdSchedulerFactory); } else if (this.configLocation != null || this.quartzProperties != null || this.taskExecutor != null || this.dataSource != null) { throw new IllegalArgumentException( "StdSchedulerFactory required for applying Quartz properties: " + schedulerFactory); } // Otherwise, no local settings to be applied via StdSchedulerFactory.initialize(Properties) } // Otherwise, assume that externally provided factory has been initialized with appropriate settings return schedulerFactory; } /** * Initialize the given SchedulerFactory, applying locally defined Quartz properties to it. * @param schedulerFactory the SchedulerFactory to initialize */ private void initSchedulerFactory(StdSchedulerFactory schedulerFactory) throws SchedulerException, IOException { Properties mergedProps = new Properties(); if (this.resourceLoader != null) { mergedProps.setProperty(StdSchedulerFactory.PROP_SCHED_CLASS_LOAD_HELPER_CLASS, ResourceLoaderClassLoadHelper.class.getName()); } if (this.taskExecutor != null) { mergedProps.setProperty(StdSchedulerFactory.PROP_THREAD_POOL_CLASS, LocalTaskExecutorThreadPool.class.getName()); } else { // Set necessary default properties here, as Quartz will not apply // its default configuration when explicitly given properties. mergedProps.setProperty(StdSchedulerFactory.PROP_THREAD_POOL_CLASS, SimpleThreadPool.class.getName()); mergedProps.setProperty(PROP_THREAD_COUNT, Integer.toString(DEFAULT_THREAD_COUNT)); } if (this.configLocation != null) { if (logger.isDebugEnabled()) { logger.debug("Loading Quartz config from [" + this.configLocation + "]"); } PropertiesLoaderUtils.fillProperties(mergedProps, this.configLocation); } CollectionUtils.mergePropertiesIntoMap(this.quartzProperties, mergedProps); if (this.dataSource != null) { mergedProps.putIfAbsent(StdSchedulerFactory.PROP_JOB_STORE_CLASS, LocalDataSourceJobStore.class.getName()); } // Determine scheduler name across local settings and Quartz properties... if (this.schedulerName != null) { mergedProps.setProperty(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, this.schedulerName); } else { String nameProp = mergedProps.getProperty(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME); if (nameProp != null) { this.schedulerName = nameProp; } else if (this.beanName != null) { mergedProps.setProperty(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, this.beanName); this.schedulerName = this.beanName; } } schedulerFactory.initialize(mergedProps); } private Scheduler prepareScheduler(SchedulerFactory schedulerFactory) throws SchedulerException { if (this.resourceLoader != null) { // Make given ResourceLoader available for SchedulerFactory configuration. configTimeResourceLoaderHolder.set(this.resourceLoader); } if (this.taskExecutor != null) { // Make given TaskExecutor available for SchedulerFactory configuration. configTimeTaskExecutorHolder.set(this.taskExecutor); } if (this.dataSource != null) { // Make given DataSource available for SchedulerFactory configuration. configTimeDataSourceHolder.set(this.dataSource); } if (this.nonTransactionalDataSource != null) { // Make given non-transactional DataSource available for SchedulerFactory configuration. configTimeNonTransactionalDataSourceHolder.set(this.nonTransactionalDataSource); } // Get Scheduler instance from SchedulerFactory. try { Scheduler scheduler = createScheduler(schedulerFactory, this.schedulerName); populateSchedulerContext(scheduler); if (!this.jobFactorySet && !(scheduler instanceof RemoteScheduler)) { // Use AdaptableJobFactory as default for a local Scheduler, unless when // explicitly given a null value through the "jobFactory" bean property. this.jobFactory = new AdaptableJobFactory(); } if (this.jobFactory != null) { if (this.applicationContext != null && this.jobFactory instanceof ApplicationContextAware applicationContextAware) { applicationContextAware.setApplicationContext(this.applicationContext); } if (this.jobFactory instanceof SchedulerContextAware schedulerContextAware) { schedulerContextAware.setSchedulerContext(scheduler.getContext()); } scheduler.setJobFactory(this.jobFactory); } return scheduler; } finally { if (this.resourceLoader != null) { configTimeResourceLoaderHolder.remove(); } if (this.taskExecutor != null) { configTimeTaskExecutorHolder.remove(); } if (this.dataSource != null) { configTimeDataSourceHolder.remove(); } if (this.nonTransactionalDataSource != null) { configTimeNonTransactionalDataSourceHolder.remove(); } } } /** * Create the Scheduler instance for the given factory and scheduler name. * Called by {@link #afterPropertiesSet}. * <p>The default implementation invokes SchedulerFactory's {@code getScheduler} * method. Can be overridden for custom Scheduler creation. * @param schedulerFactory the factory to create the Scheduler with * @param schedulerName the name of the scheduler to create * @return the Scheduler instance * @throws SchedulerException if thrown by Quartz methods * @see #afterPropertiesSet * @see org.quartz.SchedulerFactory#getScheduler */ @SuppressWarnings("NullAway") protected Scheduler createScheduler(SchedulerFactory schedulerFactory, @Nullable String schedulerName) throws SchedulerException { // Override thread context ClassLoader to work around naive Quartz ClassLoadHelper loading. Thread currentThread = Thread.currentThread(); ClassLoader threadContextClassLoader = currentThread.getContextClassLoader(); boolean overrideClassLoader = (this.resourceLoader != null && this.resourceLoader.getClassLoader() != threadContextClassLoader); if (overrideClassLoader) { currentThread.setContextClassLoader(this.resourceLoader.getClassLoader()); } try { SchedulerRepository repository = SchedulerRepository.getInstance(); synchronized (repository) { Scheduler existingScheduler = (schedulerName != null ? repository.lookup(schedulerName) : null); Scheduler newScheduler = schedulerFactory.getScheduler(); if (newScheduler == existingScheduler) { throw new IllegalStateException("Active Scheduler of name '" + schedulerName + "' already registered " + "in Quartz SchedulerRepository. Cannot create a new Spring-managed Scheduler of the same name!"); } if (!this.exposeSchedulerInRepository) { // Need to remove it in this case, since Quartz shares the Scheduler instance by default! SchedulerRepository.getInstance().remove(newScheduler.getSchedulerName()); } return newScheduler; } } finally { if (overrideClassLoader) { // Reset original thread context ClassLoader. currentThread.setContextClassLoader(threadContextClassLoader); } } } /** * Expose the specified context attributes and/or the current * ApplicationContext in the Quartz SchedulerContext. */ private void populateSchedulerContext(Scheduler scheduler) throws SchedulerException { // Put specified objects into Scheduler context. if (this.schedulerContextMap != null) { scheduler.getContext().putAll(this.schedulerContextMap); } // Register ApplicationContext in Scheduler context. if (this.applicationContextSchedulerContextKey != null) { if (this.applicationContext == null) { throw new IllegalStateException( "SchedulerFactoryBean needs to be set up in an ApplicationContext " + "to be able to handle an 'applicationContextSchedulerContextKey'"); } scheduler.getContext().put(this.applicationContextSchedulerContextKey, this.applicationContext); } } /** * Start the Quartz Scheduler, respecting the "startupDelay" setting. * @param scheduler the Scheduler to start * @param startupDelay the number of seconds to wait before starting * the Scheduler asynchronously */ protected void startScheduler(final Scheduler scheduler, final int startupDelay) throws SchedulerException { if (startupDelay <= 0) { logger.info("Starting Quartz Scheduler now"); scheduler.start(); } else { if (logger.isInfoEnabled()) { logger.info("Will start Quartz Scheduler [" + scheduler.getSchedulerName() + "] in " + startupDelay + " seconds"); } // Not using the Quartz startDelayed method since we explicitly want a daemon // thread here, not keeping the JVM alive in case of all other threads ending. Thread schedulerThread = new Thread(() -> { try { TimeUnit.SECONDS.sleep(startupDelay); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); // simply proceed } if (logger.isInfoEnabled()) { logger.info("Starting Quartz Scheduler now, after delay of " + startupDelay + " seconds"); } try { scheduler.start(); } catch (SchedulerException ex) { throw new SchedulingException("Could not start Quartz Scheduler after delay", ex); } }); schedulerThread.setName("Quartz Scheduler [" + scheduler.getSchedulerName() + "]"); schedulerThread.setDaemon(true); schedulerThread.start(); } } //--------------------------------------------------------------------- // Implementation of FactoryBean interface //--------------------------------------------------------------------- @Override public Scheduler getScheduler() { Assert.state(this.scheduler != null, "No Scheduler set"); return this.scheduler; } @Override @Nullable public Scheduler getObject() { return this.scheduler; } @Override public Class<? extends Scheduler> getObjectType() { return (this.scheduler != null ? this.scheduler.getClass() : Scheduler.class); } @Override public boolean isSingleton() { return true; } //--------------------------------------------------------------------- // Implementation of SmartLifecycle interface //--------------------------------------------------------------------- @Override public void start() throws SchedulingException { if (this.scheduler != null) { try { startScheduler(this.scheduler, this.startupDelay); } catch (SchedulerException ex) { throw new SchedulingException("Could not start Quartz Scheduler", ex); } } } @Override public void stop() throws SchedulingException { if (this.scheduler != null) { try { this.scheduler.standby(); } catch (SchedulerException ex) { throw new SchedulingException("Could not stop Quartz Scheduler", ex); } } } @Override public boolean isRunning() throws SchedulingException { if (this.scheduler != null) { try { return !this.scheduler.isInStandbyMode(); } catch (SchedulerException ex) { return false; } } return false; } //--------------------------------------------------------------------- // Implementation of DisposableBean interface //--------------------------------------------------------------------- /** * Shut down the Quartz scheduler on bean factory shutdown, * stopping all scheduled jobs. */ @Override public void destroy() throws SchedulerException { if (this.scheduler != null) { logger.info("Shutting down Quartz Scheduler"); this.scheduler.shutdown(this.waitForJobsToCompleteOnShutdown); } } } 我看到的start和你的不一样
07-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值