@Configuration
@Configuration用于定义配置类,可替换xml配置文件 ,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
被@Configuration注解的配置类有如下要求:
- @Configuration不可以是final类型。
- @Configuration不可以是匿名类。
- 匿名类:不能有名字的类,不能被引用,只能通过new关键字来声明。
- https://www.runoob.com/java/java-anonymous-class.html
-
@Bean(name=”xx”,initMethod=”start”,destroyMethod=”cleanup”)
name:bean的ID;initMethod:初始化;destroyMethod:销毁方法。
- @Bean注解在返回实例的方法上,如果未通过@Bean指定bean的名称,则默认与标注的方法名相同(第一个单词转小写)。
- @Bean注解默认作用域为单例singleton作用域,可通过@Scope(“prototype”)设置为原型作用域。
可以使用@Component、@Controller、@Service、@Ripository等替代@Bean。
@Scope
属性:
singleton(掌握):默认值,单例。
- prototype(掌握):多例(原型作用域)。
- request(了解):创建对象,把对象放到request域里。
- session(了解):创建对象,把对象放到session域里。
- globalSession(了解):创建对象,把对象放到globalSession域里。
@Bean下管理bean的生命周期
指定组建的init方法和destroy的几种方法:
代码: ```java public class Car{ public Car() {在配置类中@Bean(initMethod="init",destroyMethod="destory")注解指定
实现InitializingBean接口重写其afterPropertiesSet方法,实现DisposableBean接口重写destroy方法
利用java的JSR250规范中@PostConstruct标注在init方法上,@PreDestory标注在destroy注解上
} public void init(){System.out.println("Car's Constructor...");
} public void destory(){System.out.println("Car's Init...");
} }System.out.println("Car's Destory...");
@Bean(initMethod=”init”,destroyMethod=”destory”) public Car car(){ return new Car(); } ```