1、自定义Bean
public class Fruit {
private Integer fruitId;
private String fruitName;
private Double fruitPrice;
public Fruit() {
System.out.println("Fruit的无参数的构造方法");
}
public Fruit(Integer fruitId, String fruitName, Double fruitPrice) {
this.fruitId = fruitId;
this.fruitName = fruitName;
this.fruitPrice = fruitPrice;
System.out.println("Fruit的有参数的构造方法");
}
}
2、编写配置类
// 标记这是一个Spring配置类
@Configuration
public class SpringConfiguration {
// 如果没有@Bean注解,则注入到容器中的id就是方法名(也就是myFactoryBean),但是如果显示的给了值,那么注入到容器中的就是factoryBean
@Bean("factoryBean")
public MyFactoryBean myFactoryBean(){
return new MyFactoryBean();
}
}
3、测试类
public class SpringDemo {
@Test
public void springTest01() throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfiguration.class);
// 容器中获取的Bean,实际上就是工厂Bean(MyFactoryBean通过getObject()方法返回的对象)
Object factoryBean01 = context.getBean("factoryBean");
System.out.println("实际上注入到容器中的类型是:" + factoryBean01.getClass());
Object factoryBean02 = context.getBean("factoryBean");
System.out.println("注入到容器内的对象是否是单例:" + (factoryBean01 == factoryBean02));
Object factoryBean03 = context.getBean("&factoryBean");
System.out.println("如果想获取到MyFactoryBean的对象,使用&前缀:" + factoryBean03);
// 输出打印Spring中的所有Bean名称
String[] beanDefinitionNames = context.getBeanDefinitionNames();
for (String beanDefinitionName : beanDefinitionNames) {
System.out.println(beanDefinitionName);
}
}
}
4、测试结果
// 调用Fruit的无参数构造方法创建对象
Fruit的无参数的构造方法
// 虽然我们使用@Bean注解指定注入的是MyFactoryBean类型,但是从容器中取出来的类型依旧是我们在工厂Bean中通过getObject()方法创建的Bean的类型
实际上注入到容器中的类型是:class com.spring01.bean.Fruit
// Spring5中默认是创建单例,但是也可以重写FactoryBean中的isSinglton方法来指定单例还是多里
注入到容器内的对象是否是单例:true
// 如果你只想获取到工厂Bean的对象,需要加上一个&前缀来获取,不加前缀获取的就是工厂Bean实际创建的对象
如果想获取到MyFactoryBean的对象,使用&前缀:com.spring01.controller.MyFactoryBean@78b729e6
// Spring自身的组件
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
// Spring的配置类对象
springConfiguration
// @Bean注解注入到容器中MyFactoryBean的id,虽然id看起来是属于MyFactoryBean类型的,
// 但是实际的类型却是MyFactoryBean调用getObject()方法返回的对象
factoryBean