uot;, (person1 == person2));
}
}
proxyBeanMethods的使用
在之前提到,proxyBeanMethods
配置表示用 @Bean
注解的方法在IOC容器中是否为单例对象,默认为true。
默认情况下,打印出结果如下:
person1 是否等于 person2 ===>> true
修改一下proxyBeanMethods的值为false:
@Configuration(proxyBeanMethods = false)
public class ConfigurationAnnotationConfig {
@Bean
public Person person(){
return new Person();
}
}
打印结果如下:
person1 是否等于 person2 ===>> false
从输出结果可以看出,当@Configuration
中的proxyBeanMethods
属性为false时,每次调用@Configuration
注解标注类中被@Bean标注的方法时,都会返回不同的Bean实例对象。
创建IOC容器
传入配置类
调用AnnotationConfigApplicationContext
类的构造方法传入配置类的Class对象创建IOC容器时,可以省略配置类上的@Configuration
注解,如下:
public class ConfigurationAnnotationConfig {
@Bean
public Person person(){
return new Person();
}
}
输出结果:
person1 是否等于 person2 ===>> false
可以看到,若省略配置类上的@Configuration
注解,则每次调用配置类中被@Bean注解标注的方法时,都会返回不同的Bean实例对象,与@Configuration中设置proxyBeanMethods
的属性为false的效果相同。
传入包
调用AnnotationConfigApplicationContext
类的构造方法传入包名创建IOC容器时,不能省略配置类上的@Configuration
注解:
public class ConfigurationAnnotationConfig {
@Bean
public Person person(){
return new Person();
}
}
执行函数:
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("io.binghe.spring.annotation.chapter01.configuration");
ConfigurationAnnotationConfig config = context.getBean(ConfigurationAnnotationConfig.class);
Person person1 = config.person();
Person person2 = config.person();
LOGGER.info("person1 是否等于 person2 ===>> {}", (person1 == person2));
}
此时运行main方法,会发生报错:
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'io.binghe.spring.annotation.chapter01.configuration.config.ConfigurationAnnotationConfig' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:340)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:331)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1148)
at io.binghe.spring.annotation.chapter01.configuration.ConfigurationAnnotationTest.main(ConfigurationAnnotationTest.java:36)
添加上@Configuration
注解则程序执行正常。
扩展知识
AnnotationConfigApplicationContext
Spring在 BeanFactory
的基础上提供一些具体容器的实现。AnnotationConfigApplicationContext
就是一个用来管理注解 Bean 的容器。如下结构图:
从图中可以看到,AnnotationConfigApplicationContext
继承GenericApplicationContext
(通用应用上下文),而GenericApplicationContext
又实现了BeanDefinitionRegistry
接口,所以可以通过AnnotationConfigApplicationContext
实例类注册BeanDefintion
,然后调用refresh()
方法来初始化上下文。AnnotationConfigApplicationContext
还继承了AbstractApplicationContext
,而AbstractApplicationContext
提供了ApplicationContext
的抽象实现