xinrong2019 / xinrong2019.github.io

My Blog
https://xinrong2019.github.io
1 stars 1 forks source link

20190521之三种SpringBean的装配方式 #22

Open xinrong2019 opened 5 years ago

xinrong2019 commented 5 years ago

1、通过注解装配Bean

首先需要写一个类,在类上加上注解@Configuration,这个类就被声明为配置类,加上@Bean注解的方法,Spring会在运行时,默认以方法名为bean name,返回值类型为Bean type装配bean。

public class MyBean {
}
@Configuration//使用注解配置
public class MyConfig {

    @Bean(name = "myBean")//配置bean,默认方法名是bean name
    @Scope("prototype")//可以通过scope指定非单例
    public MyBean createMyBean(){
        return new MyBean();
    }

@Bean注解可以指定bean name,可以通过bean name和类型获取bean实例

System.out.println(context.getBean(MyBean.class));
System.out.println(context.getBean("myBean"));

还可以指定@Scope,默认单例。

输出结果:

com.baby.kim.MyBean@11c20519
com.baby.kim.MyBean@70beb599

2、通过自定义FactoryBean装配bean

通过实现FactoryBean接口,并指定泛型类,实现几个方法

//创建其他bean的bean
public class RunnableFactoryBean implements FactoryBean<Jeep> {
    @Override
    public Jeep getObject() throws Exception {
        return new Jeep();
    }

    @Override
    public Class<?> getObjectType() {
        return Jeep.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}

在配置类中装配

@Bean
    public RunnableFactoryBean createRunnableFactoryBean(){
        return new RunnableFactoryBean();
    }

使用

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        System.out.println(context.getBean("createRunnableFactoryBean"));
        System.out.println(context.getBean(Jeep.class));
        System.out.println(context.getBean(RunnableFactoryBean.class));//获取factoryBean本身
        System.out.println(context.getBean("&createRunnableFactoryBean"));
        context.close();

输出结果:

com.baby.kim.Jeep@4e41089d
com.baby.kim.Jeep@32a068d1
com.baby.kim.RunnableFactoryBean@33cb5951
com.baby.kim.RunnableFactoryBean@33cb5951

3、通过工厂装配Bean

public class Car {
}

public class CarFactory {

    public Car create(){
        return new Car();
    }
}

装配CarFactory和Car

@Bean
    public CarFactory createCarFactory(){
        return new CarFactory();
    }

    @Bean
    public Car createCar(CarFactory carFactory){
        return carFactory.create();
    }

启动类中获取

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
System.out.println(context.getBean(Car.class));
context.close();

输出结果:

com.baby.kim.Car@6a79c292