@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
一、@Configuration标注在类上,相当于把该类作为spring的xml配置文件中的<beans>
,作用为:配置spring容器(应用上下文)
@Configuration
@ComponentScan(basePackages = "com.apd.demo")
public class MyConfiguration {
public MyConfiguration(){
System.out.println("MyConfiguration初始化。。。");
}
/*
@Bean(name="exampleBean",initMethod = "init",destroyMethod = "destroy")
@Scope("prototype")
public ExampleBean exampleBean(){
return new ExampleBean();
} */
}
二、初始化spring上下文
@Test
public void testInitContext(){
//初始化方法一,applicationContext.xml在resource路径下
//ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//初始化方法二
//String conf = System.getProperty("user.dir")+File.separator+"conf"+File.separator+"applicationContext.xml";
//ApplicationContext ac = new FileSystemXmlApplicationContext(conf);
//初始化方法三,利用@Configuration
ApplicationContext ac = new AnnotationConfigApplicationContext(MyConfiguration.class)
}
三、
@Configuation等价于<Beans></Beans>
@Bean等价于<Bean></Bean>
@ComponentScan等价于<context:component-scan base-package="com.dxz.demo"/>