zoukankan      html  css  js  c++  java
  • Spring的bean创建方式ref使用方法

     java

    public class UserServiceImp implements UserService{
        private UserDao userDao =null;
        public void setUserDao(UserDao userDao) {
            this.userDao = userDao;
        }
        @Override
        public void getUser() {
            // TODO Auto-generated method stub
            userDao.getUser();
        }
    
    }

    bean

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd">
            <!-- bean 就是java对象  有spring容器创建和管理 -->
    <!--    <bean id="hello" name="cn.ioc.bean.hello">
                <property name="name" value="张三"></property>
            </bean>  -->
            <bean name="userdao" class="cn.ioc.dao.imp.UserDaoImp"></bean> 
              <bean name="othersql" class="cn.ioc.dao.imp.UserOtherSqlImp"></bean>
              <bean name="service" class="cn.ioc.service.imp.UserServiceImp">
                  <property name="userDao" ref="userdao"></property>
              </bean>

          <!-- ID是bean的标识符,是唯一的 如果没有配置id,name默认为标识符 有的话name就为别名 ,class是包名加类型 -->
          <bean id="services" name="ser1,ser2" class="cn.ioc.service.imp.UserServiceImp">
            <property name="userDao" ref="othersql"></property>  ref为引用对象
          </bean>

          <!-- 标签详解 -->
          <!-- 设置别名 -->
          <alias name="services" alias="a"/>
          <!-- 协同工作 -->
          <import resource=""/>

    </beans>

    test

    public class Test {
        public static void main(String[] args) {
            ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
            UserServiceImp usi = (UserServiceImp) ac.getBean("service");
            usi.getUser();
            UserServiceImp usis = (UserServiceImp) ac.getBean("services");
            usis.getUser();
        }
    }
  • 相关阅读:
    架构与思维:设计容量,到底有多重要 ?
    MySQL全面瓦解25:构建高性能索引(案例分析篇)
    MySQL全面瓦解24:构建高性能索引(策略篇)
    MySQL全面瓦解23:MySQL索引实现和使用
    MySQL全面瓦解22:索引的介绍和原理分析
    C#9.0:Records
    C#9.0:Improved Pattern Matching
    C#9.0:Top-Level Programs
    C#9.0:Init
    MySQL全面瓦解21(番外):一次深夜优化亿级数据分页的奇妙经历
  • 原文地址:https://www.cnblogs.com/xiaozhang666/p/11600369.html
Copyright © 2011-2022 走看看