@Configuration的proxyBeanMethods属性

本文探讨了Spring中proxyBeanMethods属性对@Bean方法调用的影响。当proxyBeanMethods为true时,方法间调用会从IOC容器获取单例对象;若设置为false,不再生成代理,可能导致多次实例化,从而产生多例。分析了proxyBeanMethods为true和false时,bashMap方法在list1和list2中的调用行为及其对性能和实例化的影响。
摘要由CSDN通过智能技术生成

        proxyBeanMethods默认为true,表示cglib会为@Configuration生成一个代理类,方法之间调用会从IOC容器去获取实例对象。因此而在list1中调用bashMap方法时,会通过代理方法从IOC容器中去获取,这样就是单例的。运行的时候,控制台只打印了一次“bashMap调用”就证明了这一点
但是如果将proxyBeanMethods设为false,则表示不生成代理,那么list1中调用bashMap,会再生成一个对象而不是从IOC容器中获取,这样能提高性能,也造成了多例。

public class ProxyBeanMethodConfig {

    @Bean
    public Map<String, Object> bashMap() {
        System.out.println("bashMap 调用了");
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("key", "this is bashMap");
        return resultMap;
    }

    @Bean
    public List<String> list1() {
        System.out.println("list1 调用了");
        Map<String, Object> map = bashMap();
        List<String> mapList = map.keySet().stream().map(row -> map.get(row).toString()).collect(Collectors.toList());
        List<String> resultList = new ArrayList<>();
        resultList.add("this is list1");
        resultList.addAll(mapList);
        return resultList;
    }

    @Bean
    public List<String> list2() {
        System.out.println("list2 调用了");
        Map<String, Object> map = bashMap();
        List<String> mapList = map.keySet().stream().map(row -> map.get(row).toString()).collect(Collectors.toList());
        List<String> resultList = new ArrayList<>();
        resultList.add("this is list2");
        resultList.addAll(mapList);
        return resultList;
    }
}

@Configuration(proxyBeanMethods = true)

 @Configuration(proxyBeanMethods = false)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值