Spring Framework 4.3.4 Учебное пособие по аннотации @Order — порядок сортировки для аннотированного компонента компонента
Опубликовано: 2017-03-04Веб-инфраструктура MVC — Spring — лучшая структура веб-контроллера и модель конфигурации для корпоративного приложения для программирования на основе Java.
На данный момент у нас есть более 40 руководств по Spring MVC на Crunchify. В этом уроке мы @Order Annotation
. Какая польза от @Order весной? Упорядочение аспектов с помощью Spring AOP
и MVC
.
Вот короткие шаги:
- Мы собираемся создать динамический веб-проект
- Создайте файл конфигурации Spring
crunchify-bean.xml
- Преобразуйте его в проект Maven
- Создание бинов с аннотацией заказа
- Создать тест-кейс и выполнить
Подробные шаги: приступим
Шаг 1
- Перейти к затмению
- Нажмите на
File
- Нажмите «
New
» - Нажмите
Dynamic Web Project
Шаг 2
- Укажите имя проекта:
CrunchifySpringMVC4OrderAnnotation
. - Обеспечьте целевую среду выполнения. В основном расположение Apache Tomcat в Eclipse.
- Выберите версию динамического веб-модуля:
3.1
.
Шаг 3
- Щелкните правой кнопкой мыши проект
- Нажмите «Настроить».
- Преобразование проекта в проект Maven
Шаг-4
Выберите настройку по умолчанию и нажмите Finish
».
Шаг-5
Вот структура проекта, прежде чем мы начнем.
Откройте файл pom.xml и добавьте зависимость Spring MVC 4.3.4.
1 2 3 4 5 |
< dependency > < groupId > org . springframework < / groupId > < artifactId > spring - context < / artifactId > < version > 4.3.4.RELEASE < / version > < / dependency > |
вот мой полный файл pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
< project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns : xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi : schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < modelVersion > 4.0.0 < / modelVersion > < groupId > CrunchifySpringMVC4OrderAnnotation < / groupId > < artifactId > CrunchifySpringMVC4OrderAnnotation < / artifactId > < version > 0.0.1 - SNAPSHOT < / version > < packaging > war < / packaging > < build > < sourceDirectory > src < / sourceDirectory > < plugins > < plugin > < artifactId > maven - compiler - plugin < / artifactId > < version > 3.3 < / version > < configuration > < source > 1.8 < / source > < target > 1.8 < / target > < / configuration > < / plugin > < plugin > < artifactId > maven - war - plugin < / artifactId > < version > 2.6 < / version > < configuration > < warSourceDirectory > WebContent < / warSourceDirectory > < failOnMissingWebXml > false < / failOnMissingWebXml > < / configuration > < / plugin > < / plugins > < / build > < dependencies > < dependency > < groupId > org . springframework < / groupId > < artifactId > spring - context < / artifactId > < version > 4.3.4.RELEASE < / version > < / dependency > < / dependencies > < / project > |
Шаг-6
- Щелкните правой кнопкой мыши ресурсы Java.
- Нажмите «Новый»
- Нажмите «Исходная папка» и укажите имя:
resources
Шаг-7
Создайте файл crunchify-bean.xml
в папке ресурсов. Вот полное содержимое файла.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<? xml version = "1.0" encoding = "UTF-8" ?> < beans xmlns = "http://www.springframework.org/schema/beans" xmlns : xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns : p = "http://www.springframework.org/schema/p" xmlns : context = "http://www.springframework.org/schema/context" xsi : schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd" > < context : annotation - config / > < ! -- Specify Bean ID "orders" -- > < bean id = "orders" class = "com.crunchify.spring.tutorials.CrunchifyPrintResult" / > < ! -- This is required and loads each class under below package -- > < context : component - scan base - package = "com.crunchify.spring.tutorials" / > < / beans > |
Шаг-8
Теперь мы создадим 5 файлов с аннотацией @Order
.
- Интерфейс CrunchifyCompany.java
- CrunchifyGoogle1.java ==> С помощью
@Order(1)
- CrunchifyFacebook2.java ==> С помощью
@Order(2)
- CrunchifyYahoo3.java ==> С помощью
@Order(3)
- CrunchifyPrintResult.java
CrunchifyCompany.java
1 2 3 4 5 6 7 8 9 10 |
package com . crunchify . spring . tutorials ; /** * @author Crunchify.com * */ public interface CrunchifyCompany { // do nothing here } |
CrunchifyGoogle1.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com . crunchify . spring . tutorials ; import org . springframework . core . annotation . Order ; import org . springframework . stereotype . Component ; /** * @author Crunchify.com * */ @Component @Order ( 1 ) // @Order defines the sort order for an annotated component. The value() is optional and represents an order value as // defined in the Ordered interface. Lower values have higher priority. The default value is // Ordered.LOWEST_PRECEDENCE, indicating lowest priority (losing to any other specified order value). public class CrunchifyGoogle1 implements CrunchifyCompany { private String order = "Crunchify Google with Order-1" ; public String toString ( ) { return "Class Name: " + this . getClass ( ) . getSimpleName ( ) + " - Result: " + this . order ; } } |

CrunchifyFacebook2.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com . crunchify . spring . tutorials ; import org . springframework . core . annotation . Order ; import org . springframework . stereotype . Component ; @Component @Order ( 2 ) public class CrunchifyFacebook2 implements CrunchifyCompany { private String order = "Crunchify Facebook with Order-2" ; public String toString ( ) { return "Class Name: " + this . getClass ( ) . getSimpleName ( ) + " - Result: " + this . order ; } } |
CrunchifyYahoo3.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com . crunchify . spring . tutorials ; import org . springframework . core . annotation . Order ; import org . springframework . stereotype . Component ; @Component @Order ( 3 ) public class CrunchifyYahoo3 implements CrunchifyCompany { private String order = "Crunchify Yahoo with Order-3" ; public String toString ( ) { return "Class Name: " + this . getClass ( ) . getSimpleName ( ) + " - Result: " + this . order ; } } |
CrunchifyPrintResult.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com . crunchify . spring . tutorials ; import java . util . List ; import org . springframework . beans . factory . annotation . Autowired ; import org . springframework . stereotype . Component ; /** * @author Crunchify.com * */ @Component public class CrunchifyPrintResult { @Autowired private List <CrunchifyCompany> order ; private String result = "" ; public String toString ( ) { order . stream ( ) . forEach ( ( temp ) - > { this . result = result + temp + "\n" ; // print result and add new line } ) ; return this . result ; } } |
Шаг-9
Теперь давайте создадим CrunchifyOrderTest.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package com . crunchify . spring . tests ; import org . springframework . context . ApplicationContext ; import org . springframework . context . support . ClassPathXmlApplicationContext ; import com . crunchify . spring . tutorials . CrunchifyPrintResult ; /** * @author Crunchify.com * */ public class CrunchifyOrderTest { @SuppressWarnings ( "resource" ) public static void main ( String [ ] args ) { // Load Spring ApplicationContext file crunchify-beans.xml ApplicationContext context = new ClassPathXmlApplicationContext ( "crunchify-beans.xml" ) ; // get the bean which we specified in file crunchify-beans.xml file CrunchifyPrintResult results = ( CrunchifyPrintResult ) context . getBean ( "orders" ) ; // After loading each class - just print result System . out . println ( results ) ; } } |
Шаг-10
Теперь просто щелкните правой кнопкой мыши файл CrunchifyOrderTest.java
и выберите « Run As
от имени» -> « Java Application
». Вы должны увидеть результат, напечатанный в том порядке, в котором мы указали Order.
1 2 3 |
Class Name : CrunchifyGoogle1 - Result : Crunchify Google with Order - 1 Class Name : CrunchifyFacebook2 - Result : Crunchify Facebook with Order - 2 Class Name : CrunchifyYahoo3 - Result : Crunchify Yahoo with Order - 3 |