Annotation Type @bean,@Import,@configuration使用--官方文档

  • @Target(value={METHOD,ANNOTATION_TYPE})
     @Retention(value=RUNTIME)
     @Documented
    public @interface Bean

    Indicates that a method produces a bean to be managed by the Spring container.

    Overview

    The names and semantics of the attributes to this annotation are intentionally similar to those of the <bean/> element in the Spring XML schema. For example:

         @Bean
         public MyBean myBean() {
             // instantiate and configure MyBean obj
             return obj;
         }

    Bean Names

    While a name attribute is available, the default strategy for determining the name of a bean is to use the name of the @Bean method. This is convenient and intuitive, but if explicit naming is desired, the nameattribute may be used. Also note that name accepts an array of Strings. This is in order to allow for specifying multiple names (i.e., aliases) for a single bean.

         @Bean(name={"b1","b2"}) // bean available as ‘b1‘ and ‘b2‘, but not ‘myBean‘
         public MyBean myBean() {
             // instantiate and configure MyBean obj
             return obj;
         }

    Scope, DependsOn, Primary, and Lazy

    Note that the @Bean annotation does not provide attributes for scope, depends-on, primary, or lazy. Rather, it should be used in conjunction with @Scope@DependsOn@Primary, and @Lazy annotations to achieve those semantics. For example:

         @Bean
         @Scope("prototype")
         public MyBean myBean() {
             // instantiate and configure MyBean obj
             return obj;
         }

    @Bean Methods in @Configuration Classes

    Typically, @Bean methods are declared within @Configuration classes. In this case, bean methods may reference other @Bean methods in the same class by calling them directly. This ensures that references between beans are strongly typed and navigable. Such so-called ‘inter-bean references‘ are guaranteed to respect scoping and AOP semantics, just like getBean() lookups would. These are the semantics known from the original ‘Spring JavaConfig‘ project which require CGLIB subclassing of each such configuration class at runtime. As a consequence, @Configuration classes and their factory methods must not be marked as final or private in this mode. For example:

     @Configuration
     public class AppConfig {
         @Bean
         public FooService fooService() {
             return new FooService(fooRepository());
         }
         @Bean
         public FooRepository fooRepository() {
             return new JdbcFooRepository(dataSource());
         }
         // ...
     }

    @Bean Lite Mode

    @Bean methods may also be declared within classes that are not annotated with @Configuration. For example, bean methods may be declared in a @Component class or even in a plain old class. In such cases, a@Bean method will get processed in a so-called ‘lite‘ mode.

    Bean methods in lite mode will be treated as plain factory methods by the container (similar to factory-method declarations in XML), with scoping and lifecycle callbacks properly applied. The containing class remains unmodified in this case, and there are no unusual constraints for the containing class or the factory methods.

    In contrast to the semantics for bean methods in @Configuration classes, ‘inter-bean references‘ are not supported in lite mode. Instead, when one @Bean-method invokes another @Bean-method in lite mode, the invocation is a standard Java method invocation; Spring does not intercept the invocation via a CGLIB proxy. This is analogous to inter-@Transactional method calls where in proxy mode, Spring does not intercept the invocation — Spring does so only in AspectJ mode.

    For example:

     @Component
     public class Calculator {
         public int sum(int a, int b) {
             return a+b;
         }
    
         @Bean
         public MyBean myBean() {
             return new MyBean();
         }
     }

    Bootstrapping

    See @Configuration Javadoc for further details including how to bootstrap the container using AnnotationConfigApplicationContext and friends.

    BeanFactoryPostProcessor-returning @Bean methods

    Special consideration must be taken for @Bean methods that return Spring BeanFactoryPostProcessor (BFPP) types. Because BFPP objects must be instantiated very early in the container lifecycle, they can interfere with processing of annotations such as @Autowired@Value, and @PostConstruct within @Configuration classes. To avoid these lifecycle issues, mark BFPP-returning @Bean methods as static. For example:

         @Bean
         public static PropertyPlaceholderConfigurer ppc() {
             // instantiate, configure and return ppc ...
         }

    By marking this method as static, it can be invoked without causing instantiation of its declaring @Configuration class, thus avoiding the above-mentioned lifecycle conflicts. Note however that static @Beanmethods will not be enhanced for scoping and AOP semantics as mentioned above. This works out in BFPP cases, as they are not typically referenced by other @Bean methods. As a reminder, a WARN-level log message will be issued for any non-static @Bean methods having a return type assignable to BeanFactoryPostProcessor.

    Since:
    3.0
    Author:
    Rod Johnson, Costin Leau, Chris Beams, Juergen Hoeller, Sam Brannen
    See Also:
    ConfigurationScopeDependsOnLazyPrimaryComponentAutowiredValue
    • Optional Element Summary

      Optional Elements
      Modifier and Type Optional Element and Description
      Autowire autowire

      Are dependencies to be injected via convention-based autowiring by name or type?

      String destroyMethod

      The optional name of a method to call on the bean instance upon closing the application context, for example a close() method on a JDBC DataSourceimplementation, or a Hibernate SessionFactory object.

      String initMethod

      The optional name of a method to call on the bean instance during initialization.

      String[] name

      The name of this bean, or if plural, aliases for this bean.

    • Element Detail

      • name

        public abstract String[] name

        The name of this bean, or if plural, aliases for this bean. If left unspecified the name of the bean is the name of the annotated method. If specified, the method name is ignored.

        Default:
        {}
      • autowire

        public abstract Autowire autowire

        Are dependencies to be injected via convention-based autowiring by name or type?

        Default:
        org.springframework.beans.factory.annotation.Autowire.NO
      • initMethod

        public abstract String initMethod

        The optional name of a method to call on the bean instance during initialization. Not commonly used, given that the method may be called programmatically directly within the body of a Bean-annotated method.

        The default value is "", indicating no init method to be called.

        Default:
        ""
      • destroyMethod

        public abstract String destroyMethod

        The optional name of a method to call on the bean instance upon closing the application context, for example a close() method on a JDBC DataSource implementation, or a Hibernate SessionFactoryobject. The method must have no arguments but may throw any exception.

        As a convenience to the user, the container will attempt to infer a destroy method against an object returned from the @Bean method. For example, given an @Bean method returning an Apache Commons DBCP BasicDataSource, the container will notice the close() method available on that object and automatically register it as the destroyMethod. This ‘destroy method inference‘ is currently limited to detecting only public, no-arg methods named ‘close‘ or ‘shutdown‘. The method may be declared at any level of the inheritance hierarchy and will be detected regardless of the return type of the @Beanmethod (i.e., detection occurs reflectively against the bean instance itself at creation time).

        To disable destroy method inference for a particular @Bean, specify an empty string as the value, e.g. @Bean(destroyMethod=""). Note that the DisposableBean and the Closeable/AutoCloseable interfaces will nevertheless get detected and the corresponding destroy/close method invoked.

        Note: Only invoked on beans whose lifecycle is under the full control of the factory, which is always the case for singletons but not guaranteed for any other scope.

        See Also:
        ConfigurableApplicationContext.close()
        Default:
        "(inferred)

官方地址:

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Bean.html

http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch02s02.html

Annotation Type Import


  • @Target(value=TYPE)
     @Retention(value=RUNTIME)
     @Documented
    public @interface Import

    Indicates one or more @Configuration classes to import.

    Provides functionality equivalent to the <import/> element in Spring XML. Only supported for classes annotated with @Configuration or declaring at least one @Bean method, as well as ImportSelector andImportBeanDefinitionRegistrar implementations.

    @Bean definitions declared in imported @Configuration classes should be accessed by using @Autowired injection. Either the bean itself can be autowired, or the configuration class instance declaring the bean can be autowired. The latter approach allows for explicit, IDE-friendly navigation between @Configuration class methods.

    May be declared at the class level or as a meta-annotation.

    If XML or other non-@Configuration bean definition resources need to be imported, use @ImportResource

    官方地址:http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Import.html

    Annotation Type Configuration


    • @Target(value=TYPE)
       @Retention(value=RUNTIME)
       @Documented
       @Component
      public @interface Configuration

      Indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime, for example:

       @Configuration
       public class AppConfig {
           @Bean
           public MyBean myBean() {
               // instantiate, configure and return bean ...
           }
       }

      Bootstrapping @Configuration classes

      Via AnnotationConfigApplicationContext

      @Configuration classes are typically bootstrapped using either AnnotationConfigApplicationContext or its web-capable variant, AnnotationConfigWebApplicationContext. A simple example with the former follows:

       AnnotationConfigApplicationContext ctx =
           new AnnotationConfigApplicationContext();
       ctx.register(AppConfig.class);
       ctx.refresh();
       MyBean myBean = ctx.getBean(MyBean.class);
       // use myBean ...

      See AnnotationConfigApplicationContext Javadoc for further details and see AnnotationConfigWebApplicationContext for web.xml configuration instructions.

      Via Spring <beans> XML

      As an alternative to registering @Configuration classes directly against an AnnotationConfigApplicationContext@Configuration classes may be declared as normal <bean> definitions within Spring XML files:

       <beans>
          <context:annotation-config/>
          <bean class="com.acme.AppConfig"/>
       </beans>

      In the example above, <context:annotation-config/> is required in order to enable ConfigurationClassPostProcessor and other annotation-related post processors that facilitate handling @Configurationclasses.

      Via component scanning

      @Configuration is meta-annotated with @Component, therefore @Configuration classes are candidates for component scanning (typically using Spring XML‘s <context:component-scan/> element) and therefore may also take advantage of @Autowired/@Inject at the field and method level (but not at the constructor level).

      @Configuration classes may not only be bootstrapped using component scanning, but may also themselves configure component scanning using the @ComponentScan annotation:

       @Configuration
       @ComponentScan("com.acme.app.services")
       public class AppConfig {
           // various @Bean definitions ...
       }

      See @ComponentScan Javadoc for details.

      Working with externalized values

      Using the Environment API

      Externalized values may be looked up by injecting the Spring Environment into a @Configuration class using the @Autowired or the @Inject annotation:

       @Configuration
       public class AppConfig {
           @Inject Environment env;
      
           @Bean
           public MyBean myBean() {
               MyBean myBean = new MyBean();
               myBean.setName(env.getProperty("bean.name"));
               return myBean;
           }
       }

      Properties resolved through the Environment reside in one or more "property source" objects, and @Configuration classes may contribute property sources to the Environment object using the @PropertySourcesannotation:

       @Configuration
       @PropertySource("classpath:/com/acme/app.properties")
       public class AppConfig {
           @Inject Environment env;
      
           @Bean
           public MyBean myBean() {
               return new MyBean(env.getProperty("bean.name"));
           }
       }

      See Environment and @PropertySource Javadoc for further details.

      Using the @Value annotation

      Externalized values may be ‘wired into‘ @Configuration classes using the @Value annotation:

       @Configuration
       @PropertySource("classpath:/com/acme/app.properties")
       public class AppConfig {
           @Value("${bean.name}") String beanName;
      
           @Bean
           public MyBean myBean() {
               return new MyBean(beanName);
           }
       }

      This approach is most useful when using Spring‘s PropertySourcesPlaceholderConfigurer, usually enabled via XML with <context:property-placeholder/>. See the section below on composing @Configurationclasses with Spring XML using @ImportResource, see @Value Javadoc, and see @Bean Javadoc for details on working with BeanFactoryPostProcessor types such as PropertySourcesPlaceholderConfigurer.

      Composing @Configuration classes

      With the @Import annotation

      @Configuration classes may be composed using the @Import annotation, not unlike the way that <import> works in Spring XML. Because @Configuration objects are managed as Spring beans within the container, imported configurations may be injected using @Autowired or @Inject:

       @Configuration
       public class DatabaseConfig {
           @Bean
           public DataSource dataSource() {
               // instantiate, configure and return DataSource
           }
       }
      
       @Configuration
       @Import(DatabaseConfig.class)
       public class AppConfig {
           @Inject DatabaseConfig dataConfig;
      
           @Bean
           public MyBean myBean() {
               // reference the dataSource() bean method
               return new MyBean(dataConfig.dataSource());
           }
       }

      Now both AppConfig and the imported DatabaseConfig can be bootstrapped by registering only AppConfig against the Spring context:

       new AnnotationConfigApplicationContext(AppConfig.class);

      With the @Profile annotation

      @Configuration classes may be marked with the @Profile annotation to indicate they should be processed only if a given profile or profiles are active:

       @Profile("embedded")
       @Configuration
       public class EmbeddedDatabaseConfig {
           @Bean
           public DataSource dataSource() {
               // instantiate, configure and return embedded DataSource
           }
       }
      
       @Profile("production")
       @Configuration
       public class ProductionDatabaseConfig {
           @Bean
           public DataSource dataSource() {
               // instantiate, configure and return production DataSource
           }
       }

      See @Profile and Environment Javadoc for further details.

      With Spring XML using the @ImportResource annotation

      As mentioned above, @Configuration classes may be declared as regular Spring <bean> definitions within Spring XML files. It is also possible to import Spring XML configuration files into @Configuration classes using the @ImportResource annotation. Bean definitions imported from XML can be injected using @Autowired or @Import:

       @Configuration
       @ImportResource("classpath:/com/acme/database-config.xml")
       public class AppConfig {
           @Inject DataSource dataSource; // from XML
      
           @Bean
           public MyBean myBean() {
               // inject the XML-defined dataSource bean
               return new MyBean(this.dataSource);
           }
       }

      With nested @Configuration classes

      @Configuration classes may be nested within one another as follows:

       @Configuration
       public class AppConfig {
           @Inject DataSource dataSource;
      
           @Bean
           public MyBean myBean() {
               return new MyBean(dataSource);
           }
      
           @Configuration
           static class DatabaseConfig {
               @Bean
               DataSource dataSource() {
                   return new EmbeddedDatabaseBuilder().build();
               }
           }
       }

      When bootstrapping such an arrangement, only AppConfig need be registered against the application context. By virtue of being a nested @Configuration class, DatabaseConfig will be registered automatically. This avoids the need to use an @Import annotation when the relationship between AppConfig DatabaseConfig is already implicitly clear.

      Note also that nested @Configuration classes can be used to good effect with the @Profile annotation to provide two options of the same bean to the enclosing @Configuration class.

      Configuring lazy initialization

      By default, @Bean methods will be eagerly instantiated at container bootstrap time. To avoid this, @Configuration may be used in conjunction with the @Lazy annotation to indicate that all @Bean methods declared within the class are by default lazily initialized. Note that @Lazy may be used on individual @Bean methods as well.

      Testing support for @Configuration classes

      The Spring TestContext framework available in the spring-test module provides the @ContextConfiguration annotation, which as of Spring 3.1 can accept an array of @Configuration Class objects:

       @RunWith(SpringJUnit4ClassRunner.class)
       @ContextConfiguration(classes={AppConfig.class, DatabaseConfig.class})
       public class MyTests {
      
           @Autowired MyBean myBean;
      
           @Autowired DataSource dataSource;
      
           @Test
           public void test() {
               // assertions against myBean ...
           }
       }

      See TestContext framework reference documentation for details.

      Enabling built-in Spring features using @Enable annotations

      Spring features such as asynchronous method execution, scheduled task execution, annotation driven transaction management, and even Spring MVC can be enabled and configured from @Configurationclasses using their respective "@Enable" annotations. See @EnableAsync@EnableScheduling@EnableTransactionManagement@EnableAspectJAutoProxy, and @EnableWebMvc for details.

      Constraints when authoring @Configuration classes

      • @Configuration classes must be non-final
      • @Configuration classes must be non-local (may not be declared within a method)
      • @Configuration classes must have a default/no-arg constructor and may not use @Autowired constructor parameters. Any nested configuration classes must be static.

    官方地址:http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Configuration.html

时间: 2024-10-13 11:37:58

Annotation Type @bean,@Import,@configuration使用--官方文档的相关文章

Spring Framework 官方文档学习(四)之Validation、Data Binding、Type Conversion

前言 在Spring Framework官方文档中,这三者是放到一起讲的,但没有解释为什么放到一起.大概是默认了读者都是有相关经验的人,但事实并非如此,例如我.好在闷着头看了一遍,又查资料又敲代码,总算明白了. 其实说穿了一文不值,我们用一个例子来解释: 假定,现有一个app,功能是接收你输入的生日,然后显示你的年龄.看起来app只要用当前日期减去你输入的日期就是年龄,应该很简单对吧?可惜事实不是这样的. 这里面有三个问题: 问题一:我们输入的永远是字符串,字符串需要转成日期格式才能被我们的ap

TestNG官方文档中文版(2)-annotation(转)

1. 介绍    TestNG是一个设计用来简化广泛的测试需求的测试框架,从单元测试(隔离测试一个类)到集成测试(测试由有多个类多个包甚至多个外部框架组成的整个系统,例如运用服务器). 编写一个测试的过程有三个典型步骤: * 编写测试的 业务逻辑并在代码中插入TestNG annotation    * 将测试信息添加到testng.xml文件或者build.xml中    * 运行TestNG 在欢迎页面上可以找到快速入门示例. 下面是这篇文档使用的概念: * suite由xml文件描述.它包

Spark官方文档: Spark Configuration(Spark配置)

Spark官方文档: Spark Configuration(Spark配置) Spark主要提供三种位置配置系统: 环境变量:用来启动Spark workers,可以设置在你的驱动程序或者conf/spark-env.sh 脚本中: java系统性能:可以控制内部的配置参数,两种设置方法: 编程的方式(程序中在创建SparkContext之前,使用System.setProperty("xx","xxx")语句设置相应系统属性值): 在conf/spark-env

Spring Cloud官方文档中文版-声明式Rest客户端:Feign

官方文档地址为:http://cloud.spring.io/spring-cloud-static/Dalston.SR2/#spring-cloud-feign 文中例子我做了一些测试在:http://git.oschina.net/dreamingodd/spring-cloud-preparation Declarative REST Client: Feign 声明式Rest客户端:Feign Feign is a declarative web service client. It

Spring JMS 官方文档学习

最后部分的XML懒得写了,因为个人更倾向于JavaConfig形式. 为知笔记版本见这里,带格式~ 做了一个小demo,放到码云上了,有兴趣的点我. 说明:需要先了解下JMS的基础知识. 1.介绍 Spring 提供了一个JMS集成框架,简化了JMS API的使用,类似于Spring提供的JDBC API集成. JMS可以粗略地划分成两大功能区域,就是消息的生产(production)和消费(consumption).JmsTemplate 用于消息的生产和同步的消息接收.对于异步消息接收,类似

Spring Boot 官方文档入门及使用

个人说明:本文内容都是从为知笔记上复制过来的,样式难免走样,以后再修改吧.另外,本文可以看作官方文档的选择性的翻译(大部分),以及个人使用经验及问题. 其他说明:如果对Spring Boot没有概念,请先移步上一篇文章 Spring Boot 学习.本篇原本是为了深入了解下Spring Boot而出现的. 另外,Spring Boot 仍然是基于Spring的,建议在赶完工之后深入学习下Spring,有兴趣可以看看我的 Spring 4 官方文档学习(十一)Web MVC 框架 .欢迎探讨,笑~

Spring Cloud官方文档中文版-服务发现:Eureka客户端

官方文档地址为:http://cloud.spring.io/spring-cloud-static/Brixton.SR7/#_spring_cloud_netflix 文中例子我做了一些测试在:http://git.oschina.net/dreamingodd/spring-cloud-preparation Spring Cloud Netflix This project provides Netflix OSS integrations for Spring Boot apps th

hbase官方文档(转)

Apache HBase™ 参考指南  HBase 官方文档中文版 Copyright © 2012 Apache Software Foundation.保留所有权利. Apache Hadoop, Hadoop, MapReduce, HDFS, Zookeeper, HBase 及 HBase项目 logo 是Apache Software Foundation的商标. Revision History Revision 0.95-SNAPSHOT 2012-12-03T13:38 中文版

JavaBeans 官方文档学习

提示,重点:JavaBeans的Property和 Events:PropertyEditor极其注册和查找机制. 从目前来看,JavaBeans 更像是源自GUI的需求. 使用NetBeans新建一个Java Application,然后新建一个jFrame form,右边会有组件面板,如下: 这些组件,本质上都是bean!所以可被复用.可被引用.可被通知! 将任意一个组件拖进去安置,例如Button(按钮).如下: 在右下角会显示该组件的属性,如下: 如果是英文版的NetBeans,你就会发