spring boot 单例bean中使用多例bean

ServiceA

@Component
@Scope("prototype")
public class ServiceA {
}
ServiceB 
@Service
public class ServiceB implements ApplicationContextAware {
    public void say(){
        ServiceA serviceA = this.getServiceA();
        System.out.println("this:"+this+",serviceA:"+ serviceA);
    }
    public ServiceA getServiceA() {
        return this.context.getBean(ServiceA.class);
    }
    private ApplicationContext context;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
}

测试:

@SpringBootApplication
public class SpringBootRedisClientExampleApplication {

    public static void main(String[] args) {
        ApplicationContext run = SpringApplication.run(SpringBootRedisClientExampleApplication.class, args);
        System.out.println();
        ServiceB serviceB = run.getBean(ServiceB.class);
        serviceB.say();
        serviceB.say();
    }
}

结果:

 

posted @ 2023-02-22 14:17  亮sir  阅读(264)  评论(0编辑  收藏  举报