代码之家  ›  专栏  ›  技术社区  ›  FreezY

@自动连线会话范围bean未指向同一实例

  •  1
  • FreezY  · 技术社区  · 10 年前

    我在春天给豆子自动布线时遇到了这种奇怪的情况。首先我申报这个豆子;

    <beans:bean id="customerInfo" class="my.web.app.com.CustomerInfoSession" scope="session" >
        <aop:scoped-proxy />
    </beans:bean>
    

    当我将值设置为 客户信息 ;

    首先,我这样设置:

    SqlRowSet srs =jdbcTemplate.queryForRowSet(query, qparams);
        if (srs.isBeforeFirst()==true) {
            while (srs.next()) {
                customerInfo.setLoginId(srs.getString("LOGINID"));
                customerInfo.setCompanyId(srs.getString("COMPANYID"));
            }
        }
    System.out.println("Instance : "+customerInfo);//for first pointing check
    

    然后我通过@Autowiredthebean检查另一个类中的Autowired指针;

    在测试类中:

    @Controller
    public class Test {
    
    @Autowired
    private CustomerInfoSession customerInfo;
    
    public void checkObject(){
    System.out.println("Call back : "+customerInfo);//for second pointing check
    }
    
    }
    

    后果 :

    实例:my.web.app.com.CustomerInfoSession@1e7c92cc

    回电:my.web.app.com.CustomerInfoSession@1e7c92cc

    正如我们所看到的,@Autowiring正在调用它应该调用的bean实例,但当我更改为这样设置值时,问题出现了:

    customerInfo = (CustomerInfoSession) jdbcTemplate.queryForObject(query,qparam,new BeanPropertyRowMapper<>(CustomerInfoSession.class));
    System.out.println("Instance : "+customerInfo);//for first pointing check
    

    通过使用相同的Test类 后果 是:

    实例:my.web.app.com.CustomerInfoSession@2d700bd6

    回电:my.web.app.com.CustomerInfoSession@5e33e39c

    如我们所见,@Autowired不指向同一实例。。。

    为什么使用不同的jdbc模板会影响@Autowired会话范围bean?

    为什么bean没有指向与它应该指向的相同的实例?

    1 回复  |  直到 10 年前
        1
  •  1
  •   Madhusudana Reddy Sunnapu    10 年前

    在第一个场景中,您正在设置Spring注入的对象的属性。

    但在下一种情况下, jdbcTemplate 正在创建的新实例 CustomerInfoSession 您指向的对象 customerInfo objectref指向这个新创建的对象。

    以下陈述

    customerInfo=(CustomerInfoSession)jdbcTemplate。queryForObject(查询,qparam,新BeanPropertyRowMapper<>(CustomerInfoSession.class));

    实际上相当于

    CustomerInfoSession临时=(CustomerInfoSession) jdbcTemplate。queryForObject(查询, 新BeanPropertyRowMapper<>(CustomerInfoSession.class));

    customerInfo=临时;

    为了可视化(单击下面的图像以更好地查看),

    在情况1中:

    enter image description here

    在情况2:

    enter image description here