In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "the method of reading configuration files by Spring". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1 、 XMLBeanFcatory
BeanFactory bf = new XmlBeanFactory (new ClassPathResource ("beanFactory.xml")); public class XmlBeanFactory extends DefaultListableBeanFactory {/ / core code, XmlBeanFactory uses custom XmlBeanDefinitionReader to read XML file XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader (this); public XmlBeanFactory (Resource resource, BeanFactory parentBeanFactory) {/ / read XML configuration file core code this.reader.loadBeanDefinitions (resource);}} 2, configuration file encapsulation
You can load resource files using classes provided by Spring, such as
Resource resource = new ClassPathResource ("beanFactory.xml"); / / getInputStream is the only method defined in InputStreamResource, and it is also the top interface InputStream inputStream = resource.getInputStream () encapsulated by Spring for resources.
Public interface InputStreamSource {InputStream getInputStream () throws IOException;} public interface Resource extends InputStreamSource {boolean exists (); boolean isReadable (); boolean isOpen (); URL getURL () throws IOException; URI getURI () throws IOException; File getFile () throws IOException; long contentLength () throws IOException; long lastModified () throws IOException; Resource createRelative (String relativePath) throws IOException; String getFilename (); String getDescription ();} 3. Load resource files
After using new ClassPathResource to encapsulate the resource file as Resource, you can use XmlBeanDefinitionReader to read the configuration file.
BeanFactory bf = new XmlBeanFactory (new ClassPathResource ("beanFactory.xml")); public XmlBeanFactory (Resource resource, BeanFactory parentBeanFactory) {this.reader.loadBeanDefinitions (resource);} public int loadBeanDefinitions (Resource resource) {/ / EncodedResource is mainly used for return loadBeanDefinitions (new EncodedResource (resource)) to encode resource files;} public int loadBeanDefinitions (EncodedResource encodedResource) throws BeanDefinitionStoreException {/ / records loaded resources through Set, which is placed in ThreadLocal Set currentResources = resourcesCurrentlyBeingLoaded.get () If (currentResources = = null) {currentResources = new HashSet (4); / / put this.resourcesCurrentlyBeingLoaded.set (currentResources) in ThreadLocal;} if (! currentResources.add (encodedResource)) {throw new BeanDefinitionStoreException ();} try {/ / get the file input stream, which has been analyzed above InputStream inputStream = encodedResource.getResource (). GetInputStream (); try {InputSource inputSource = new InputSource (inputStream) If (encodedResource.getEncoding ()! = null) {inputSource.setEncoding (encodedResource.getEncoding ());} / / really enters the logic core of the read. The inputSource passed here is org.xml.sax.InputResource, which is used for sax parsing return doLoadBeanDefinitions (inputSource, encodedResource.getResource ()). }} protected int doLoadBeanDefinitions (InputSource inputSource, Resource resource) {try {/ / step 1, get the verification mode of the XML file. The method used by Spring to verify the verification mode is to determine whether it contains DOCTYPE, if it contains DTD, otherwise it is XSD int validationMode = getValidationModeForResource (resource). / / step 2, load the XML file and get the corresponding Document Document doc = this.documentLoader.loadDocument (inputSource, getEntityResolver (), this.errorHandler, validationMode, isNamespaceAware ()); / / step 3, register the Bean information return registerBeanDefinitions (doc, resource) according to the returned Bean } / / step 2public Document loadDocument (InputSource inputSource, EntityResolver entityResolver, ErrorHandler errorHandler, int validationMode, boolean namespaceAware) {/ / SAX parses the XML document and returns the Document object DocumentBuilderFactory factory = createDocumentBuilderFactory (validationMode, namespaceAware); DocumentBuilder builder = createDocumentBuilder (factory, entityResolver, errorHandler); return builder.parse (inputSource);} / / step 3public int registerBeanDefinitions (Document doc, Resource resource) {BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader (); / / set the environment variable documentReader.setEnvironment (this.getEnvironment ()) / / record the number of Bean defined in BeanDefinition int countBefore = getRegistry (). GetBeanDefinitionCount (); documentReader.registerBeanDefinitions (doc, createReaderContext (resource)); / / return the number of BeanDefinition loaded this time return getRegistry (). GetBeanDefinitionCount ()-countBefore;} 4, start parsing documentReader.registerBeanDefinitions (doc, createReaderContext (resource)); public void registerBeanDefinitions (Document doc, XmlReaderContext readerContext) {this.readerContext = readerContext / / read root element, displayed in debug as [beans: null] Element root = doc.getDocumentElement (); doRegisterBeanDefinitions (root);} protected void doRegisterBeanDefinitions (Element root) {/ / handles profile element. Profile tag can be used to configure production environment, development environment, etc. String profileSpec = root.getAttribute (PROFILE_ATTRIBUTE); if (StringUtils.hasText (profileSpec)) {Assert.state (this.environment! = null, "Environment must set for evaluating profiles") String [] specifiedProfiles = StringUtils.tokenizeToStringArray (profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS); if (! this.environment.acceptsProfiles (specifiedProfiles)) {return;}} / / Agent that specializes in parsing BeanDefinitionParserDelegate parent = this.delegate; this.delegate = createDelegate (this.readerContext, root, parent) / / the two methods here are empty implementations and are designed for inheritance, which is the template method pattern. Subclasses can inherit and do some processing before parsing: preProcessXml (root); parseBeanDefinitions (root, this.delegate); postProcessXml (root); this.delegate = parent;} protected void parseBeanDefinitions (Element root, BeanDefinitionParserDelegate delegate) {if (delegate.isDefaultNamespace (root)) {NodeList nl = root.getChildNodes (); for (int I = 0) I < nl.getLength (); iTunes +) {Node node = nl.item (I); if (node instanceof Element) {Element ele = (Element) node; if (delegate.isDefaultNamespace (ele)) {/ / resolve default tags, such as bean parseDefaultElement (ele, delegate) } else {/ / parse custom tags, such as delegate.parseCustomElement (ele);}} else {delegate.parseCustomElement (root);}} "Spring implements the method of reading configuration files". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 218
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.