@Configuration

@Configuration用于定义配置类,可替换xml配置文件 ,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
被@Configuration注解的配置类有如下要求:

  1. @Configuration不可以是final类型。
  2. @Configuration不可以是匿名类。
    1. 匿名类:不能有名字的类,不能被引用,只能通过new关键字来声明。
    2. https://www.runoob.com/java/java-anonymous-class.html
  3. 嵌套的@Configuration必须是静态的。

    @Bean(name=”xx”,initMethod=”start”,destroyMethod=”cleanup”)

  4. name:bean的ID;initMethod:初始化;destroyMethod:销毁方法。

  5. @Bean注解在返回实例的方法上,如果未通过@Bean指定bean的名称,则默认与标注的方法名相同(第一个单词转小写)。
  6. @Bean注解默认作用域为单例singleton作用域,可通过@Scope(“prototype”)设置为原型作用域。
  7. 可以使用@Component、@Controller、@Service、@Ripository等替代@Bean。

    @Scope

    属性:

  8. singleton(掌握):默认值,单例。

  9. prototype(掌握):多例(原型作用域)。
  10. request(了解):创建对象,把对象放到request域里。
  11. session(了解):创建对象,把对象放到session域里。
  12. globalSession(了解):创建对象,把对象放到globalSession域里。

    @Bean下管理bean的生命周期

    指定组建的init方法和destroy的几种方法:
    1. 在配置类中@Bean(initMethod="init",destroyMethod="destory")注解指定
    2. 实现InitializingBean接口重写其afterPropertiesSet方法,实现DisposableBean接口重写destroy方法
    3. 利用javaJSR250规范中@PostConstruct标注在init方法上,@PreDestory标注在destroy注解上
    代码: ```java public class Car{ public Car() {
    1. System.out.println("Car's Constructor...");
    } public void init(){
    1. System.out.println("Car's Init...");
    } public void destory(){
    1. System.out.println("Car's Destory...");
    } }

@Bean(initMethod=”init”,destroyMethod=”destory”) public Car car(){ return new Car(); } ```