Spring JSR-250 annotations -2 (auto-detect the Spring components)

2010-03-29  来源:本站原创  分类:Java  人气:469 

From the 2.0 version of the beginning, Spring introduced stereotypes (stereotype) the concept of annotations as well as @ Repository annotation tags as the data access code approach. On this basis, Spring2.5 also added two new annotations - @ Service and @ Controller to complete the usual three-tier architecture (data access objects, services, web controllers) the role of the appointment. Spring2.5 also introduced the generic @ Component annotation and other stereotypes can be logically extended them. Through the application clearly indicate the role that these stereotypes facilitated Spring AOP and post-processor use, these post-processor to a role based on these annotation objects added to provide additional behavior. For example, Spring2.0 introduced PersistenceExceptionTranslationPostProcessor any object with the @ Repository annotation activated automatically convert their data access exceptions.

These annotations can also be combined Spring2.5 to use some other new features: Automatic detection of components on the classpath. While XML has become the most common format for metadata Spring, but it is by no means the only option. In fact, Spring container meta-data is expressed by a pure Java, when XML is used to define when the Spring managed objects, in the instance of the process before, those definitions are parsed and transformed into Java objects. Spring2.5's a great new feature is support for reading annotations from the source level metadata. Thus, the mechanism described above the use of automatic assembly metadata annotations to inject dependencies, but it still need to register at least one bean definition in order to provide the realization of each Spring managed object class. Component scanning function was to make this XML in the bean definition of the minimum requirements of no longer exists.

As shown above, Spring annotation-driven auto-assembly can be fine-grained control without sacrificing a great extent under the premise of reducing the use of XML. Component detection mechanism would be even better this advantage. A comprehensive alternative to XML in the configuration is no longer necessary, component scan but can handle XML metadata to simplify the overall configuration. Combination of XML and annotation-driven technology can be a balanced optimization method, which is version 2.5 of the PetClinic examples described in detail. In the example, the infrastructure components (data source, transaction management, etc.) combined with the externalization of the above-mentioned properties are defined in the XML. Data access layer objects as well as some defined in the XML, they have also made use of the configuration @ Autowired annotations to simplify the dependency injection. Finally, web-layer controller is not one explicitly defined in XML, on the contrary, this configuration provided below is used to trigger the automatic detection of all web controllers:

<context:component-scan base-package="org.springframework.samples.petclinic.web"/>


Important to note that this example of the use to the base-package attribute. Component matching rules will be scanned recursively by default to detect the package (multiple packages can provide a comma-separated list) of all classes in all of Spring stereotype annotations. Because of this, PetClinic application examples of the types of controller implementations using @ Controller annotation (Spring, one of the built-in stereotypes). See the following example:

@ Controller public class ClinicController (private final Clinic clinic; @ Autowired public ClinicController (Clinic clinic) (this.clinic = clinic;)


Auto-detect component registered in the Spring container, just as they are defined as XML. As indicated above, those objects could be rotated to use annotation-driven auto-assembly.

Component matching rules can be scanned through the filter (filter) from the definition, in accordance with the type, AspectJ expression, or against the naming patterns regular expressions to determine which components to include or not include. Default stereotypes can also be disabled. For example there is a configuration example, this configuration will ignore the default stereotype, but it will automatically detect Stub name to begin with or contain @ Mock annotation for all classes:

<context:component-scan base-package="example" use-default-filters="false"> <context:include-filter type="aspectj" expression="example..Stub*"/> <context: include - filter type = "annotation" expression = "example.Mock" /> </ context: component-scan>


Restrictive type of match can also be used exclusive control of the filter. For example, in addition to the other outside the @ Repository annotation rely on the default filter, then we need to join an exclusive filter (exclude-filter).

<context:component-scan base-package="example"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/> </ context: component-scan>


Obviously, there are many ways to extend component scanning to register a custom type. Structure-based annotation is the simplest choice, so the concept itself is a stereotype can be extensible. Like previously mentioned, @ Component is a generic model, @ Repository, @ Service, and @ Controller annotations are the logical extension from the stereotypes derived. Because of this, @ Component can be used as a meta-annotation (that is, in another comment on the statement notes), all annotated with @ Component yuan custom annotations are scanned by default matching rules automatically detected. An example there is the hope that you are aware of the fact that it did not sound so difficult.

Let us recall the talking @ PostConstruct and @ PreDestroy life-cycle when the annotation of the hypothetical background tasks. Perhaps an application there are many many such background tasks that require an instance of XML bean definition in order to be registered in the Spring context and make their own life-cycle approach is called at the right time. The use of components of scanning is no longer needed an explicit XML bean definitions. If these background tasks to achieve a common interface, or followed the same naming convention, you can use include-filters. However, a more simple way is to create an object for these tasks and provide annotation @ Component meta-annotation.

@ Target ((ElementType.TYPE)) @ Retention (RetentionPolicy.RUNTIME) @ Documented @ Component public @ interface BackgroundTask (String value () default "";)


Then in all the background tasks of the class definition to provide a custom stereotype annotations.

@ BackgroundTask public class FilePoller (@ PostConstruct public void startPolling () () @ PreDestroy public void stopPolling () ())


Generic @ Component annotation can be provided as an example as simple to use, custom annotation technique provides a use of more meaning, the name of domain-specific opportunities. These domain-specific annotations to provide more in-depth opportunities, such as the use of AspectJ pointcut expressions to identify all the background tasks, in order to increase advice to monitor the activity of these tasks.

By default, when the components are detected, Spring will automatically generate a modifier is not the name of the class name as the bean. The previous example, the generated bean name will be filePoller. However, any filling of the Spring stereotype annotation (@ Component, @ Repository, @ Service, or @ Controller), or filling the other with @ Component as a meta-annotation of annotations (such as in the example above, @ BackgroundTask) classes, Structure-based annotation value attribute can be explicitly specified, the instance of the value of the bean as its name in the register context. The next case, the instance name should be petClinic instead of the default generated name simpleJdbcClinic.

@ Service ( "petClinic") public class SimpleJdbcClinic ()


Similarly, in the following revised version of the FilePoller example, the generated bean name should be the poller instead filePoller.

@ BackgroundTask ( "poller") public class FilePoller ()


Although all Spring managed objects are by default treated as a single instance of cases to handle, but sometimes still need to specify an alternate target for a range (scope). For example, in the web layer, a Spring managed object may be tied to the request or session scope. For version 2.0, Spring's scope systems more scalable, this way, the custom scope can be registered to the application context (application context). In the XML configuration, is just simply included into the scope and the scope attribute's name on it.

<bean scope="session"> </ bean>


Spring2.5 in, in order to be scanned @ Scope annotation component provides can play the same role.

@ Component @ Scope ( "session") public class ShoppingCart ()


Here we must point out that last point is to use the component scan qualifier annotation application is how simple. In the previous section, the following objects have been using a custom qualifier annotations as automatic assembly example:

@ VetSpecialty ( "dentistry") private Clinic dentistryClinic;


Similar examples in the XML and then show the use of 'qualifier' element to provide specific target bean definition of dependent. When using component scanning, XML metadata is not required. However, since the definition of modifiers may be in the target class definition was introduced as a type of annotation layer. Another will be scanned @ Repository instance as an example dependence is as follows:

@ Repository @ VetSpecialty ( "dentistry") public class DentistryClinic implements Clinic ()


In the end, because of the previous example demonstrates a custom annotation and its attributes example, equal with the non-dependent on target XML as follows:

@ Repository @ SpecializedClinic (species = "dog", breed = "poodle") public class PoodleClinic implements Clinic ()


Summary

Spring2.5 in many ways provides a very interesting new features. This article focuses on how to force through the control of Java annotations to simplify the configuration. As defined in the JSR-250 as, Spring support public annotations (Common Annotations), while an automated assembly process to provide a more fine-grained control over additional notes. Spring2.5 also extends from the Spring2.0 the @ Repository on the beginning of stereotypes (stereotype) annotations, and all of these stereotype annotations and new components can be combined with scanning capabilities. Spring2.5 still in full support XML-based configuration, the same time it introduces a new namespace context of the common configuration scenarios provide a more incisive grammar. Indeed, support for XML and annotation-based configuration seamlessly integrated end-to generate a more balanced and comprehensive approach. The basic framework of the complex configuration can be defined in the module XML file, while the growing stack of applications to higher-level configuration can be further from the annotation-based technologies to benefit - the premise is all in the same application context within a Spring2.5 .

相关文章
  • Configuration Spring 2.5 annotations 2010-06-30

    Introduction From the beginning of the birth, Spring framework to adhere to its purpose: streamlining enterprise application development, complex problems simultaneously to provide a strong, non-invasive solution. Spring2.0 released a year ago, put t

  • Integrated struts2 spring hibernate, using annotations 2011-05-08

    Integrated struts2 spring hibernate, using annotations 2009-04-24 10:43 Integrate struts, spring, hibernate, the biggest problem for beginners on its cumbersome xml configuration file. Now all of which are annotation-based configuration provides good

  • JAVA using Spring AOP with annotations for the system to increase logging 2010-04-20

    Spring Spring AOP has always been a more distinctive features, it can use existing code in any place, we would like to embed the logic function, and do not need to change our existing code structure. In view of this, the present system has completed

  • Using spring AOP and annotations to resolve logs 2010-03-31

    First, create a custom annotation @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface RecordLog { } Then uses spring Aop @Component("logAround") public class LogAroundInterceptor implements MethodInterceptor { @Au

  • Configuring ehcache spring 2.5 annotations 2010-12-09

    Configuring ehcache Address: http://code.google.com/p/ehcache-spring-annotations/wiki/UsingTriggersRemove hi: Hello everybody, I am currently using spring ehcache as the project's cache. Detailed configuration is as follows: ehcaceh_config.xml <? Xml

  • 2010 Spring Festival Evening program for the 2010 CCTV Spring Festival Evening program for the latest version of 2008-07-15

    We look forward to the Spring Festival Evening program for coming out ahead of the secrets in your heart opened. For more please refer to Web site: Speakers 1. Opening song, "Yimeng Mountain Minor" dj Allegro 2. Folk song "Everybody come to

  • spring web flow 2 and the velocity integrated spring mvc 2010-03-24

    First, add the following code in the web.xml <!-- Character Encoding filter --> <filter> <filter-name>encodingFilter</filter-name> <filter-class> org.springframework.web.filter.CharacterEncodingFilter </filter-class> &l

  • spring security3.x学习(25)_bean配置跑spring security 2014-02-02

    本文为转载学习 原文链接:http://blog.csdn.net/dsundsun/article/details/11972811 看spring security有一段时间了,一直迷惑于spring security使用的不方便,今天看书的时候,终于提到了自定义的spring security,下边就是书中提出的神图(我是看了一下,没怎么看懂,但是我觉得自己做完再回来看肯定就差不多了.) 直接看配置文件: <!-- 配置一个定义的过滤器链 --> <bean id="sp

  • (二)在一的基础上集成spring 4.0.3 并整合JPA以及spring的单元测试 2014-05-02

    1)加上sping的依赖包,并在base模块进行引用. <!-- spring包依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency&

  • Spring.net + FluorineFx project structures of the four. Spring.net database calls written 2010-09-12

    Fourth, the database call 4.1 Dao class methods General operation of the database, new, query, modify, delete 4.1.1 New data written Add a staff, incoming data: the names of persons, the sector key; return after additional personnel key. C # Code / /

  • From the spring of ioc ioc class diagram to see spring's design 2011-01-10

    AliasRegistry: Provides registration, delete, access, and whether the method is an alias. BeanDefinitionRegistry: Provides registration, delete, access, and whether the definition includes methods such as bean, and inherited AliasRegistry. SimpleAlia

  • Spring MVC 3.1 Update - 绝好的Spring MVC 3.1学习资料共112页 2012-03-09

    http://rstoyanchev.github.com/spring-mvc-31-update/#1 点此链接,用方向键盘播放和回退 enjoy it 原文链接:http://blog.csdn.net/kimsoft/article/details/7104516

  • Detailed annotations Spring 2011-01-04

    Based on comments (Annotation) configuration has become increasingly popular trend, Spring 2.5 conform to this trend, providing a complete annotation based configuration Bean, Bean the assembly function, you can use Spring IoC-based annotation replac

  • Spring JSR-250 annotations -2 (auto-detect the Spring components) 2010-03-29

    From the 2.0 version of the beginning, Spring introduced stereotypes (stereotype) the concept of annotations as well as @ Repository annotation tags as the data access code approach. On this basis, Spring2.5 also added two new annotations - @ Service

  • Spring Annotations Learning Letters (6) test 2010-02-13

    Since the system is based on notes self-contained, then the test based on whether it can rely on Spring annotation easy to complete? Resolutely No problem! Spring-Test duty-bound to complete this task! And, through the Spring-Test of the transaction

  • Spring Annotations Learning Letters (2) control layer comb 2010-08-04

    Spring notes yesterday have a whole understanding, at least to complete a simple web application structure. Of course, not perfect, this is only the beginning! Today saw Spring 3.0 annotations, I feel that they have been subverted. Years ago, in orde

  • Spring Annotations Learning Letters (4) persistence of 2010-08-04

    Today, we play with the database and work on the persistence layer. Not to pursue things too complicated, Spring annotations for the persistence of the transformation is not hard to understand! We use the most direct interpretation of Spring JdbcTemp

  • Kernel of Spring - the relationship between the management of three bean (auto assembly) 2010-10-06

    Spring BeanFactory provides similar automated assembly of components in the pico container dependent objects function. Automatic assembly can be applied to each component, some components can be defined for the automatic assembly, while other compone

  • Double Spring MVC annotations and XML configuration 2010-11-03

    Spring usually derived using the WebService, in order to be able to use Spring MVC Annotations for Controller in both configuration and use of XML configuration, as follows: Java code <! - Start Spring MVC's annotations, POJO to complete the mapping

  • With Spring 2.0 and AspectJ simplify the enterprise application 2010-04-23

    http://hi.baidu.com/jmugis/blog/item/78d9d60af8fc5b1c94ca6bc7.html Spring: Simple and powerful Spring's goal is to make enterprise application development simple and efficient as possible. Of this theory can be an instance of Spring's JDBC, ORM, JMX,