@Configuration
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
@Target(ElementType.TYPE):注解作用在类上
@Retention(RetentionPolicy.RUNTIME):保留策略 —> 运行时保留
@Documented:表明这个注解应该被 javadoc工具记录. 默认情况下,javadoc是不包括注解的.
@Component: 表明这个类也会被注入到spring容器中
我们再来看下注释对@Configuration的解释
Indicates that a class declares one or more {@link Bean @Bean} methods and
may be processed by the Spring container to generate bean definitions and
service requests for those beans at runtime
通过上述解释可以看出@Configuration注解的类成为一个配置类,在配置类里声明了@Bean的方法会交给spring容器管理。也就是说@Configuration标记的类等同于下面的Spring XML配置文件。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- bean definitions here -->
</beans>
演示
新建一个实体类
package org.example.entity;
public class HelloWord {
public void sayHello(){
System.out.println("this is sayHello method");
}
}
1.通过传统xml方式注册bean
配置文件:bean.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- bean definitions here -->
<bean id="helloWord" class="org.example.entity.HelloWord"/>
</beans>
测试:
@Test
public void testXmlConfig(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
HelloWord helloWord = (HelloWord) context.getBean("helloWord");
helloWord.sayHello();
}
结果:
this is sayHello method
2.通过注解的方式注册bean
配置类:
package org.example.config;
import org.example.entity.HelloWord;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class HelloWordConfig {
@Bean
public HelloWord helloWord(){
return new HelloWord();
}
}
测试:
@Test
public void testConfigurationAnno(){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(HelloWordConfig.class);
HelloWord helloWord = (HelloWord) context.getBean("helloWord");
helloWord.sayHello();
}
结果:
this is sayHello method
注意:我们前面也分析到了@Configuration被@Component修饰,说明@Configuration注解的类也会加入到spring容器,我们来测试一下
@Test
public void testConfigurationAnno(){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(HelloWordConfig.class);
Arrays.stream(context.getBeanDefinitionNames()).forEach(
c->{
System.out.println(c);
}
);
}
结果:
image.png
通过结果可以看出HelloWordConfig类和HelloWord类都被注册到Spring容器中了。