Classpathxmlapplicationcontext где ищет файл
Standalone XML application context, taking the context definition files from the class path, interpreting plain paths as class path resource names that include the package path (e.g. "mypackage/myresource.txt"). Useful for test harnesses as well as for application contexts embedded within JARs.
The config location defaults can be overridden via AbstractRefreshableConfigApplicationContext.getConfigLocations() , Config locations can either denote concrete files like "/myfiles/context.xml" or Ant-style patterns like "/myfiles/*-context.xml" (see the AntPathMatcher javadoc for pattern details).
Note: In case of multiple config locations, later bean definitions will override ones defined in earlier loaded files. This can be leveraged to deliberately override certain bean definitions via an extra XML file.
This is a simple, one-stop shop convenience ApplicationContext. Consider using the GenericApplicationContext class in combination with an XmlBeanDefinitionReader for more flexible context setup.
ClassPathXmlApplicationContext
ClassPathXmlApplicationContext
ClassPathXmlApplicationContext
Create a new ClassPathXmlApplicationContext, loading the definitions from the given XML file and automatically refreshing the context.
Parameters: configLocation - resource location Throws: BeansException - if context creation failed
ClassPathXmlApplicationContext
Create a new ClassPathXmlApplicationContext, loading the definitions from the given XML files and automatically refreshing the context.
Parameters: configLocations - array of resource locations Throws: BeansException - if context creation failed
ClassPathXmlApplicationContext
Create a new ClassPathXmlApplicationContext with the given parent, loading the definitions from the given XML files and automatically refreshing the context.
Parameters: configLocations - array of resource locations parent - the parent context Throws: BeansException - if context creation failed
ClassPathXmlApplicationContext
Parameters: configLocations - array of resource locations refresh - whether to automatically refresh the context, loading all bean definitions and creating all singletons. Alternatively, call refresh manually after further configuring the context. Throws: BeansException - if context creation failed See Also: AbstractApplicationContext.refresh()
ClassPathXmlApplicationContext
Create a new ClassPathXmlApplicationContext with the given parent, loading the definitions from the given XML files.
Parameters: configLocations - array of resource locations refresh - whether to automatically refresh the context, loading all bean definitions and creating all singletons. Alternatively, call refresh manually after further configuring the context. parent - the parent context Throws: BeansException - if context creation failed See Also: AbstractApplicationContext.refresh()
ClassPathXmlApplicationContext
Create a new ClassPathXmlApplicationContext, loading the definitions from the given XML file and automatically refreshing the context.
This is a convenience method to load class path resources relative to a given Class. For full flexibility, consider using a GenericApplicationContext with an XmlBeanDefinitionReader and a ClassPathResource argument.
Parameters: path - relative (or absolute) path within the class path clazz - the class to load resources with (basis for the given paths) Throws: BeansException - if context creation failed See Also: ClassPathResource.ClassPathResource(String, Class) , GenericApplicationContext , XmlBeanDefinitionReader
ClassPathXmlApplicationContext
Create a new ClassPathXmlApplicationContext, loading the definitions from the given XML files and automatically refreshing the context.
Parameters: paths - array of relative (or absolute) paths within the class path clazz - the class to load resources with (basis for the given paths) Throws: BeansException - if context creation failed See Also: ClassPathResource.ClassPathResource(String, Class) , GenericApplicationContext , XmlBeanDefinitionReader
ClassPathXmlApplicationContext
Create a new ClassPathXmlApplicationContext with the given parent, loading the definitions from the given XML files and automatically refreshing the context.
getConfigResources
Description copied from class: AbstractXmlApplicationContext Return an array of Resource objects, referring to the XML bean definition files that this context should be built with.
The default implementation returns null . Subclasses can override this to provide pre-built Resource objects rather than location Strings.
Пару месяцев назад в моем профиле был опубликован подробный пост по загрузке классов на JVM. После этого доклада мои коллеги задались хорошим вопросом: а какой механизм использует Spring для разбора конфигураций и как он загружает классы из контекста?
После многих часов дебага спринговых исходников мой коллега экспериментальным путём докопался до той самой простой и понятной правды.
Немного теории
Сразу определим, что ApplicationContext — это главный интерфейс в Spring-приложении, который предоставляет информацию о конфигурации приложения.
Перед тем, как перейти непосредственно к демонстрации, взглянем на этапы формирования ApplicationContext:
В этом посте разберем первый этап, так как нас интересует именно чтение конфигураций и создание BeanDefinition.
BeanDefinition — это интерфейс, который описывает бин, его свойства, аргументы конструктора и другую метаинформацию.
Что касается конфигурации самих бинов, у Spring есть 4 способа конфигурации:
- Xml конфигурация — ClassPathXmlApplicationContext(”context.xml”);
- Groovy конфигурация — GenericGroovyApplicationContext(”context.groovy”);
- Конфигурация через аннотации с указанием пакета для сканирования — AnnotationConfigApplicationContext(”package.name”);
- JavaConfig — конфигурация через аннотации с указанием класса (или массива классов) помеченного аннотацией @Configuration — AnnotationConfigApplicationContext(JavaConfig.class).
Xml конфигурация
За основу берем простой проект:
Здесь следует немного пояснить, какие методы и для чего используются:
- printLoadedClasses(String… filters) — метод выводит в консоль название загрузчика и загруженных JVM классов из пакета, переданного как параметр. Дополнительно есть информация о количестве всех загруженных классов;
- doSomething(Object o) — метод, который делает примитивную работу, но не позволяет исключить упомянутые классы в процессе оптимизации при компиляции.
В 25 строке идет объявление и инициализация ApplicationContext через конфигурацию Xml.
Конфигурационный Xml-файл выглядит следующим образом:
При конфигурации бина указываем реально существующий class. Обратите внимание на заданное свойство lazy-init=”true”: в этом случае бин будет создаваться только после запроса его из контекста.
Смотрим, как Spring при поднятии контекста разрулит ситуацию с классами, объявленными в конфигурационном файле:
Разберемся с деталями Xml конфигурации:
— Чтением файла конфигурации занимается класс XmlBeanDefinitionReader, который реализует интерфейс BeanDefinitionReader;
— XmlBeanDefinitionReader на входе получает InputStream и загружает Document через DefaultDocumentLoader:
— После этого каждый элемент этого документа обрабатывается и, если он является бином, создается BeanDefinition на основе заполненных данных (id, name, class, alias, init- method, destroy-method и др.):
— Каждый BeanDefinition помещается в Map, который хранится в классе DefaultListableBeanFactory:
В коде Map выглядит следующим образом:
Теперь в том же конфигурационном файле добавим еще одно объявление бина с классом film.BadVillain:
Смотрим, что получится, если распечатать список созданных BeanDefenitionNames и загруженные классы:
Несмотря на то, что класса film.BadVillain, указанного в конфигурационном файле, не существует, Spring отрабатывает без ошибок:
Cписок BeanDefenitionNames содержит 2 элемента; то есть, те 2
BeanDefinition, сконфигурированные в нашем файле, были созданы.
Конфигурации обоих бинов, по сути, одинаковы. Но, при этом существующий класс загрузился, никаких проблем не возникло. Из чего можно сделать вывод, что попытка загрузить несуществующий класс также была, но провальная попытка ничего не сломала.
Попытаемся получить еще и сами бины по их именам:
Если в первом случае был получен валидный бин, то во втором случае прилетел exception.
Обратите внимание на stack trace: сработала отложенная загрузка классов. Выполняется обход всех загрузчиков классов в попытке найти искомый класс среди загруженных ранее. И после того, как нужный класс не был найден, с помощью вызова метода Utils.forName, происходит попытка найти несуществующий класс по имени, что привело к получению закономерной ошибки.
При поднятии контекста загрузился только один класс, при этом попытка загрузки несуществующего файла не привела к ошибке. Почему так произошло?
Всё потому, что мы прописали lazy-init:true и запретили Spring создавать экземпляр бина, где и генерируется полученный ранее exception. Если убрать это свойство из конфигурации либо изменить его значение lazy-init:false, то описанная выше ошибка также вылетит, но не будет проигнорирована и приложение остановиться. В нашем случае контекст был проинициализирован, но мы не смогли создать экземпляр бина, т.к. указанный класс не был найден.
Groovy конфигурация
При конфигурации контекста с помощью Groovy-файла, необходимо сформировать GenericGroovyApplicationContext, который принимает на вход строку с конфигурацией контекста. Чтением контекста в данном случае занимается класс GroovyBeanDefinitionReader. Эта конфигурация работает по сути так же, как и Xml, только с Groovy-файлами. К тому же, GroovyApplicationContext нормально работает и с Xml-файлом.
Пример простого конфигурационного Groovy-файла:
Пробуем проделать то же самое, что и с Xml:
Ошибка вылетает сразу: Groovy так же, как и Xml, создает BeanDefenition'ы, но в данном случае постпроцессор сразу выдаёт ошибку.
Конфигурация через аннотации с указанием пакета для сканирования или JavaConfig
Данная конфигурация отличается от двух предыдущих. В конфигурация через аннотации используется 2 варианта: JavaConfig и аннотация над классами.
Здесь используется один и тот же контекст: AnnotationConfigApplicationContext(“package”/JavaConfig.class). Работает он в зависимости от того, что было передано в конструктор.
В контексте AnnotationConfigApplicationContext есть 2 приватных поля:
- private final AnnotatedBeanDefinitionReader reader (работает с JavaConfig);
- private final ClassPathBeanDefinitionScanner scanner (сканирует пакет).
Создаем конфигурационный файл с максимально простым бином. Смотрим, что загрузится:
Если в случае с Xml и Groovy загрузилось столько BeanDefinition, сколько было объявлено, то в данном случае в процессе поднятия контекста загружаются как объявленные, так и дополнительные BeanDefinition. В случае реализации через JavaConfig все классы загружаются сразу, в том числе и класс самого JavaConfig, так как он сам является бином.
Еще один момент: в случае с Xml и Groovy конфигурациями загрузилось 343 файла, здесь же произошла более “тяжелая” загрузка количеством 631 доп файл.
Этапы работы ClassPathBeanDefinitionScanner:
- По указанному пакету определяется список файлов для сканирования. Все файлы попадают в директории;
- Сканер проходит по каждому файлу, получает InputStream и сканирует при помощи класса org.springframework.asm.ClassReader.class;
- На 3-ем этапе сканер проверяет, проходят ли найденные объекты по фильтрам аннотации org.springframework.core.type.filter.AnnotationTypeFilter. По умолчанию Spring ищет классы, которые помечены аннотацией Component либо любой другой аннотацией, которая включает в себя Component;
- Если проверка проходит успешно, создаются и регистрируются новые BeanDefinition.
Рассмотрим работу сканера на простом примере.
Создаем собственную аннотацию для поиска соответствующих классов:
Создаем 2 класса: один со стандартной аннотацией Component, второй — с кастомной аннотацией:
В результате получаем сформированные BeanDefinition для этих классов и успешно загруженные классы.
Вывод
Из всего вышесказанного на поставленные вопросы можно ответить следующим образом:
Всех, кого интересует внутреннее устройство Spring, прошу под кат.
На схеме изображены основные этапы поднятия ApplicationContext. В этом посте мы остановимся на каждом из этих этапов. Какой-то этап будет рассмотрен подробно, а какой-то будет описан в общих чертах.
1. Парсирование конфигурации и создание BeanDefinition
- Xml конфигурация — ClassPathXmlApplicationContext(“context.xml”)
- Конфигурация через аннотации с указанием пакета для сканирования — AnnotationConfigApplicationContext(“package.name”)
- Конфигурация через аннотации с указанием класса (или массива классов) помеченного аннотацией @Configuration -AnnotationConfigApplicationContext(JavaConfig.class). Этот способ конфигурации называется — JavaConfig.
- Groovy конфигурация — GenericGroovyApplicationContext(“context.groovy”)
Цель первого этапа — это создание всех BeanDefinition. BeanDefinition — это специальный интерфейс, через который можно получить доступ к метаданным будущего бина. В зависимости от того, какая у вас конфигурация, будет использоваться тот или иной механизм парсирования конфигурации.
Xml конфигурация
Для Xml конфигурации используется класс — XmlBeanDefinitionReader, который реализует интерфейс BeanDefinitionReader. Тут все достаточно прозрачно. XmlBeanDefinitionReader получает InputStream и загружает Document через DefaultDocumentLoader. Далее обрабатывается каждый элемент документа и если он является бином, то создается BeanDefinition на основе заполненных данных (id, name, class, alias, init-method, destroy-method и др.). Каждый BeanDefinition помещается в Map. Map хранится в классе DefaultListableBeanFactory. В коде Map выглядит вот так.
Конфигурация через аннотации с указанием пакета для сканирования или JavaConfig
Конфигурация через аннотации с указанием пакета для сканирования или JavaConfig в корне отличается от конфигурации через xml. В обоих случаях используется класс AnnotationConfigApplicationContext.
Если заглянуть во внутрь AnnotationConfigApplicationContext, то можно увидеть два поля.
ClassPathBeanDefinitionScanner сканирует указанный пакет на наличие классов помеченных аннотацией @Component (или любой другой аннотацией которая включает в себя @Component). Найденные классы парсируются и для них создаются BeanDefinition.
Чтобы сканирование было запущено, в конфигурации должен быть указан пакет для сканирования.
Groovy конфигурация
Данная конфигурация очень похожа на конфигурацию через Xml, за исключением того, что в файле не XML, а Groovy. Чтением и парсированием groovy конфигурации занимается класс GroovyBeanDefinitionReader.
2. Настройка созданных BeanDefinition
После первого этапа у нас имеется Map, в котором хранятся BeanDefinition. Архитектура спринга построена таким образом, что у нас есть возможность повлиять на то, какими будут наши бины еще до их фактического создания, иначе говоря мы имеем доступ к метаданным класса. Для этого существует специальный интерфейс BeanFactoryPostProcessor, реализовав который, мы получаем доступ к созданным BeanDefinition и можем их изменять. В этом интерфейсе всего один метод.
Метод postProcessBeanFactory принимает параметром ConfigurableListableBeanFactory. Данная фабрика содержит много полезных методов, в том числе getBeanDefinitionNames, через который мы можем получить все BeanDefinitionNames, а уже потом по конкретному имени получить BeanDefinition для дальнейшей обработки метаданных.
Давайте разберем одну из родных реализаций интерфейса BeanFactoryPostProcessor. Обычно, настройки подключения к базе данных выносятся в отдельный property файл, потом при помощи PropertySourcesPlaceholderConfigurer они загружаются и делается inject этих значений в нужное поле. Так как inject делается по ключу, то до создания экземпляра бина нужно заменить этот ключ на само значение из property файла. Эта замена происходит в классе, который реализует интерфейс BeanFactoryPostProcessor. Название этого класса — PropertySourcesPlaceholderConfigurer. Весь этот процесс можно увидеть на рисунке ниже.
Давайте еще раз разберем что же у нас тут происходит. У нас имеется BeanDefinition для класса ClassName. Код класса приведен ниже.
Если PropertySourcesPlaceholderConfigurer не обработает этот BeanDefinition, то после создания экземпляра ClassName, в поле host проинжектится значение — "$" (в остальные поля проинжектятся соответсвующие значения). Если PropertySourcesPlaceholderConfigurer все таки обработает этот BeanDefinition, то после обработки, метаданные этого класса будут выглядеть следующим образом.
Соответственно в эти поля проинжектятся правильные значения.
Для того что бы PropertySourcesPlaceholderConfigurer был добавлен в цикл настройки созданных BeanDefinition, нужно сделать одно из следующих действий.
Для XML конфигурации.
PropertySourcesPlaceholderConfigurer обязательно должен быть объявлен как static. Без static у вас все будет работать до тех пор, пока вы не попробуете использовать @ Value внутри класса @Configuration.
3. Создание кастомных FactoryBean
FactoryBean — это generic интерфейс, которому можно делегировать процесс создания бинов типа . В те времена, когда конфигурация была исключительно в xml, разработчикам был необходим механизм с помощью которого они бы могли управлять процессом создания бинов. Именно для этого и был сделан этот интерфейс. Для того что бы лучше понять проблему, приведу пример xml конфигурации.
На первый взгляд, тут все нормально и нет никаких проблем. А что делать если нужен другой цвет? Создать еще один бин? Не вопрос.
А что делать если я хочу каждый раз случайный цвет? Вот тут то и приходит на помощь интерфейс FactoryBean.
Создадим фабрику которая будет отвечать за создание всех бинов типа — Color.
Добавим ее в xml и удалим объявленные до этого бины типа — Color.
Теперь создание бина типа Color.class будет делегироваться ColorFactory, у которого при каждом создании нового бина будет вызываться метод getObject.
Для тех кто пользуется JavaConfig, этот интерфейс будет абсолютно бесполезен.
4. Создание экземпляров бинов
Созданием экземпляров бинов занимается BeanFactory при этом, если нужно, делегирует это кастомным FactoryBean. Экземпляры бинов создаются на основе ранее созданных BeanDefinition.
5. Настройка созданных бинов
Интерфейс BeanPostProcessor позволяет вклиниться в процесс настройки ваших бинов до того, как они попадут в контейнер. Интерфейс несет в себе несколько методов.
- Оба метода в итоге должны вернуть бин. Если в методе вы вернете null, то при получении этого бина из контекста вы получите null, а поскольку через бинпостпроцессор проходят все бины, после поднятия контекста, при запросе любого бина вы будете получать фиг, в смысле null.
- Если вы хотите сделать прокси над вашим объектом, то имейте ввиду, что это принято делать после вызова init метода, иначе говоря это нужно делать в методе postProcessAfterInitialization.
Процесс донастройки показан на рисунке ниже. Порядок в котором будут вызваны BeanPostProcessor не известен, но мы точно знаем что выполнены они будут последовательно.
Для того, что бы лучше понять для чего это нужно, давайте разберемся на каком-нибудь примере.
При разработке больших проектов, как правило, команда делится на несколько групп. Например первая группа разработчиков занимается написанием инфраструктуры проекта, а вторая группа, используя наработки первой группы, занимается написанием бизнес логики. Допустим второй группе понадобился функционал, который позволит в их бины инжектить некоторые значения, например случайные числа.
На первом этапе будет создана аннотация, которой будут помечаться поля класса, в которые нужно проинжектить значение.
По умолчанию, диапазон случайных числе будет от 0 до 10.
Затем, нужно создать обработчик этой аннотации, а именно реализацию BeanPostProcessor для обработки аннотации InjectRandomInt.
Код данного BeanPostProcessor достаточно прозрачен, поэтому мы не будем на нем останавливаться, но тут есть один важный момент.
BeanPostProcessor обязательно должен быть бином, поэтому мы его либо помечаем аннотацией @Component, либо регестрируем его в xml конфигурации как обычный бин.
Первая группа разработчиков свою задачу выполнила. Теперь вторая группа может использовать эти наработки.
Хочу сказать отдельное спасибо EvgenyBorisov. Благодаря его курсу, я решился на написание этого поста.
An application context constructor (for a specific application context type) generally takes a string or array of strings as the location path(s) of the resource(s) such as XML files that make up the definition of the context.
When such a location path doesn't have a prefix, the specific Resource type built from that path and used to load the bean definitions, depends on and is appropriate to the specific application context. For example, if you create a ClassPathXmlApplicationContext as follows:
The bean definitions will be loaded from the classpath, as a ClassPathResource will be used. But if you create a FileSystemXmlApplicationContext as follows:
The bean definition will be loaded from a filesystem location, in this case relative to the current working directory.
Note that the use of the special classpath prefix or a standard URL prefix on the location path will override the default type of Resource created to load the definition. So this FileSystemXmlApplicationContext .
. will actually load its bean definitions from the classpath. However, it is still a FileSystemXmlApplicationContext . If it is subsequently used as a ResourceLoader , any unprefixed paths will still be treated as filesystem paths.
4.7.1.1 Constructing ClassPathXmlApplicationContext instances - shortcuts
The ClassPathXmlApplicationContext exposes a number of constructors to enable convenient instantiation. The basic idea is that one supplies merely a string array containing just the filenames of the XML files themselves (without the leading path information), and one also supplies a Class ; the ClassPathXmlApplicationContext will derive the path information from the supplied class.
An example will hopefully make this clear. Consider a directory layout that looks like this:
A ClassPathXmlApplicationContext instance composed of the beans defined in the 'services.xml' and 'daos.xml' could be instantiated like so.
Please do consult the Javadocs for the ClassPathXmlApplicationContext class for details of the various constructors.
4.7.2 Wildcards in application context constructor resource paths
The resource paths in application context constructor values may be a simple path (as shown above) which has a one-to-one mapping to a target Resource, or alternately may contain the special "classpath*:" prefix and/or internal Ant-style regular expressions (matched using Spring's PathMatcher utility). Both of the latter are effectively wildcards
One use for this mechanism is when doing component-style application assembly. All components can 'publish' context definition fragments to a well-known location path, and when the final application context is created using the same path prefixed via classpath*: , all component fragments will be picked up automatically.
Note that this wildcarding is specific to use of resource paths in application context constructors (or when using the PathMatcher utility class hierarchy directly), and is resolved at construction time. It has nothing to do with the Resource type itself. It's not possible to use the classpath*: prefix to construct an actual Resource , as a resource points to just one resource at a time.
4.7.2.1 Ant-style Patterns
When the path location contains an Ant-style pattern, for example:
Implications on portability
If the specified path is already a file URL (either explicitly, or implicitly because the base ResourceLoader is a filesystem one, then wildcarding is guaranteed to work in a completely portable fashion.
If the specified path is a classpath location, then the resolver must obtain the last non-wildcard path segment URL via a Classloader.getResource() call. Since this is just a node of the path (not the file at the end) it is actually undefined (in the ClassLoader Javadocs) exactly what sort of a URL is returned in this case. In practice, it is always a java.io.File representing the directory, where the classpath resource resolves to a filesystem location, or a jar URL of some sort, where the classpath resource resolves to a jar location. Still, there is a portability concern on this operation.
4.7.2.2 The classpath*: prefix
When constructing an XML-based application context, a location string may use the special classpath*: prefix:
This special prefix specifies that all classpath resources that match the given name must be obtained (internally, this essentially happens via a ClassLoader.getResources(. ) call), and then merged to form the final application context definition.
The wildcard classpath relies on the getResources() method of the underlying classloader. As most application servers nowadays supply their own classloader implementation, the behavior might differ especially when dealing with jar files. A simple test to check if classpath* works is to use the classloader to load a file from within a jar on the classpath: getClass().getClassLoader().getResources("") . Try this test with files that have the same name but are placed inside two different locations. In case an inappropriate result is returned, check the application server documentation for settings that might affect the classloader behavior.
The " classpath*: " prefix can also be combined with a PathMatcher pattern in the rest of the location path, for example " classpath*:META-INF/*-beans.xml ". In this case, the resolution strategy is fairly simple: a ClassLoader.getResources() call is used on the last non-wildcard path segment to get all the matching resources in the class loader hierarchy, and then off each resource the same PathMatcher resoltion strategy described above is used for the wildcard subpath.
4.7.2.3 Other notes relating to wildcards
Please note that " classpath*: " when combined with Ant-style patterns will only work reliably with at least one root directory before the pattern starts, unless the actual target files reside in the file system. This means that a pattern like " classpath*:*.xml " will not retrieve files from the root of jar files but rather only from the root of expanded directories. This originates from a limitation in the JDK's ClassLoader.getResources() method which only returns file system locations for a passed-in empty string (indicating potential roots to search).
Ant-style patterns with " classpath: " resources are not guaranteed to find matching resources if the root package to search is available in multiple class path locations. This is because a resource such as
may be in only one location, but when a path such as
is used to try to resolve it, the resolver will work off the (first) URL returned by getResource("com/mycompany") ;. If this base package node exists in multiple classloader locations, the actual end resource may not be underneath. Therefore, preferably, use " classpath*: " with the same Ant-style pattern in such a case, which will search all class path locations that contain the root package.
4.7.3 FileSystemResource caveats
A FileSystemResource that is not attached to a FileSystemApplicationContext (that is, a FileSystemApplicationContext is not the actual ResourceLoader ) will treat absolute vs. relative paths as you would expect. Relative paths are relative to the current working directory, while absolute paths are relative to the root of the filesystem.
For backwards compatibility (historical) reasons however, this changes when the FileSystemApplicationContext is the ResourceLoader . The FileSystemApplicationContext simply forces all attached FileSystemResource instances to treat all location paths as relative, whether they start with a leading slash or not. In practice, this means the following are equivalent:
As are the following: (Even though it would make sense for them to be different, as one case is relative and the other absolute.)
In practice, if true absolute filesystem paths are needed, it is better to forgo the use of absolute paths with FileSystemResource / FileSystemXmlApplicationContext , and just force the use of a UrlResource , by using the file: URL prefix.
Standalone XML application context, taking the context definition files from the class path, interpreting plain paths as class path resource names that include the package path (e.g. "mypackage/myresource.txt"). Useful for test harnesses as well as for application contexts embedded within JARs.
The config location defaults can be overridden via AbstractRefreshableConfigApplicationContext.getConfigLocations() , Config locations can either denote concrete files like "/myfiles/context.xml" or Ant-style patterns like "/myfiles/*-context.xml" (see the AntPathMatcher javadoc for pattern details).
Note: In case of multiple config locations, later bean definitions will override ones defined in earlier loaded files. This can be leveraged to deliberately override certain bean definitions via an extra XML file.
This is a simple, one-stop shop convenience ApplicationContext. Consider using the GenericApplicationContext class in combination with an XmlBeanDefinitionReader for more flexible context setup.
Nested Class Summary
Nested classes/interfaces inherited from class org.springframework.core.io.DefaultResourceLoader
Field Summary
Fields inherited from class org.springframework.context.support.AbstractApplicationContext
Fields inherited from interface org.springframework.context.ConfigurableApplicationContext
Fields inherited from interface org.springframework.beans.factory.BeanFactory
Fields inherited from interface org.springframework.core.io.support.ResourcePatternResolver
Fields inherited from interface org.springframework.core.io.ResourceLoader
Constructor Summary
Create a new ClassPathXmlApplicationContext, loading the definitions from the given XML files and automatically refreshing the context.
Create a new ClassPathXmlApplicationContext, loading the definitions from the given XML file and automatically refreshing the context.
Create a new ClassPathXmlApplicationContext with the given parent, loading the definitions from the given XML files and automatically refreshing the context.
Create a new ClassPathXmlApplicationContext with the given parent, loading the definitions from the given XML files.
Create a new ClassPathXmlApplicationContext, loading the definitions from the given XML files and automatically refreshing the context.
Create a new ClassPathXmlApplicationContext with the given parent, loading the definitions from the given XML files and automatically refreshing the context.
Create a new ClassPathXmlApplicationContext, loading the definitions from the given XML file and automatically refreshing the context.
Method Summary
Modifier and Type | Method and Description |
---|---|
protected Resource[] | getConfigResources () |
Return an array of Resource objects, referring to the XML bean definition files that this context should be built with.
Methods inherited from class org.springframework.context.support.AbstractXmlApplicationContext
Methods inherited from class org.springframework.context.support.AbstractRefreshableConfigApplicationContext
Methods inherited from class org.springframework.context.support.AbstractRefreshableApplicationContext
Methods inherited from class org.springframework.context.support.AbstractApplicationContext
Methods inherited from class org.springframework.core.io.DefaultResourceLoader
Methods inherited from class java.lang.Object
Methods inherited from interface org.springframework.context.ConfigurableApplicationContext
Methods inherited from interface org.springframework.core.io.ResourceLoader
Constructor Detail
ClassPathXmlApplicationContext
ClassPathXmlApplicationContext
ClassPathXmlApplicationContext
Create a new ClassPathXmlApplicationContext, loading the definitions from the given XML file and automatically refreshing the context.
ClassPathXmlApplicationContext
Create a new ClassPathXmlApplicationContext, loading the definitions from the given XML files and automatically refreshing the context.
ClassPathXmlApplicationContext
Create a new ClassPathXmlApplicationContext with the given parent, loading the definitions from the given XML files and automatically refreshing the context.
ClassPathXmlApplicationContext
ClassPathXmlApplicationContext
Create a new ClassPathXmlApplicationContext with the given parent, loading the definitions from the given XML files.
ClassPathXmlApplicationContext
Create a new ClassPathXmlApplicationContext, loading the definitions from the given XML file and automatically refreshing the context.
This is a convenience method to load class path resources relative to a given Class. For full flexibility, consider using a GenericApplicationContext with an XmlBeanDefinitionReader and a ClassPathResource argument.
ClassPathXmlApplicationContext
Create a new ClassPathXmlApplicationContext, loading the definitions from the given XML files and automatically refreshing the context.
ClassPathXmlApplicationContext
Create a new ClassPathXmlApplicationContext with the given parent, loading the definitions from the given XML files and automatically refreshing the context.
Method Detail
getConfigResources
Return an array of Resource objects, referring to the XML bean definition files that this context should be built with.
The default implementation returns null . Subclasses can override this to provide pre-built Resource objects rather than location Strings.
Читайте также: