【Spring reference】Spring基于java的配置

1、简述

    spring reference写到:

Java-based configuration: Starting with Spring 3.0, many features provided by the Spring JavaConfig project became part of the core Spring Framework. Thus you can define beans external to your application classes by using Java rather than XML files. To use these new features, see the @Configuration, @Bean , @Importand @DependsOnannotations.
    jast领会到:

从Spring3.0开始支持使用java代码来代替XML来配置Spring,基于Java配置Spring依靠Spring的JavaConfig项目提供的很多优点。通过使用@Configuration,
@Bean ,@Importand,@DependsOnannotations来实现Java的配置Spring.  


2、基于Java的Spring的配置(Java-based container configuration)

    基本概念:@Bean 和@Configuration

    在Spring的新的Java-Configuration的中间产物是基于类的@Configuration的注解和基于方法的@Bean注解。

    @Bean注解是用来指明方法的实例化,配置和初始化一个对象是通过Spring的IoC容器来管理的。对于那些熟悉使用以XML配置Spring的<beans /> 标签,@Bean注解和<bean />标签是起相同作用的。你能和Spring的@Component注解的组件一起使用@Bean注解方法, 然而,这些@Bean注解的方法通常是和@Configuration的Bean。

    @Configuration注解的类指明该类主要是作为一个bean的来源定义。此外,@Configurationd定义的classes允许在同一个类中使用@Bean定义的方法来定义依赖的bean。以下是一个尽可能简单的用@Configuration定义的class:

@Configuration
public class AppConfig {
    @Bean
    publicMyService myService() {
        return newMyServiceImpl();
    }
}

    上面定义的AppConfig类和以下使用xml的<beans/>标签定义是等价物。 

<beans>
<bean id="myService" class="com.acme.services.MyServiceImpl"/>
</beans>

    接下来,深入讨论下注解@Bean和注解@Configuration,首先,不管怎样,我们将涵盖所用方式使用基于Java的配置来创建一个Spring的容器。

    Spring reference写到:    

Full @Configuration vs lite@Beans mode? 
When @Beanmethods are declared within classes that are notannotated with @Configuration they are referred to as being processed in a litemode. For example, bean methods declared in a @Componentor even in a plain old classwill be considered lite. 
Unlike full @Configuration, lite @Beanmethods cannot easily declare inter-bean dependencies. Usually one @Beanmethod should not invoke another @Beanmethod when operating in litemode.

 Only using @Beanmethods within @Configurationclasses is a recommended approach of ensuring that fullmode is always used. This will prevent the same @Beanmethod from accidentally being invoked multiple times and helps to reduce subtle bugs that can be hard to track down when operating in litemode.

    译为:

        完整的@Configuration VS 简单的@Bean模式

    当@Bean修饰方法是

   

    使用AnnotationConfigApplicationContext初始化Spring容器

    






你可能感兴趣的:(spring)