zoukankan      html  css  js  c++  java
  • @Autowired获取配置文件中被注入实例的两种方式

    一、说明

    二、那么在JavaBean中如何通过@Autowired获取该实例呢?有两种方式:

    1.直接获取

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:applicationContext_test.xml") 
    public class MyTest1 {
        @Autowired
        private HibernateTemplate hibernateTemplate;//获取在applicationContext_test.xml中被注入的HibernateTemplate实例  
    
        //获取HibernateTemplate的实例
        @Test
        public void getHibernateTemplateInstance(){
            System.out.println(hibernateTemplate);//org.springframework.orm.hibernate3.HibernateTemplate@eb5d53
        }
       
    }

    2.间接获取

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:applicationContext_test.xml") 
    public class MyTest1 {
        private HibernateTemplate hibernateTemplate;
        @Autowired             //获取HibernateTemplate实例并本地化(即将该实例赋给本类中已声明的hibernateTemplate属性)
        public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {  
            this.hibernateTemplate = hibernateTemplate;  
        } 
    
        //获取HibernateTemplate的实例
        @Test
        public void getHibernateTemplateInstance(){
            System.out.println(hibernateTemplate);//org.springframework.orm.hibernate3.HibernateTemplate@eb5d53
        }
        
    }

     小结:通过以上两种方式可以了解到@Autowired注入Bean主要用在字段上火set方法上。

  • 相关阅读:
    canvas-绘制矩形-读书笔记
    获取页面路径中的参数
    微信小程序引用组件的方式
    this指向知识梳理
    for循环整理
    微信小程序使用wxs(小程序的一套脚本语言)
    textarea层级过高的解决办法
    防止用户连续点击按钮导致页面数据重复
    微信小程序tab切换
    HTML/CSS 知识点01 (转)
  • 原文地址:https://www.cnblogs.com/wql025/p/4818123.html
Copyright © 2011-2022 走看看