zoukankan      html  css  js  c++  java
  • Spring注入

    Spring依赖注入之set方式

    1.在PerDaoImpl中定义属性及set方法(PerDaoImpl类)

    private int pid;

    private String pname;

    public void SetPid(int pid){

    this.pid=pid;

    }

    public void SetPname(int pname){

    this.pname=pname;

    }

    2.配置文件中为属性赋值(beans.xml)

    通过set方法为属性赋值,根据name属性去查找对应的set方法,将value值作为形参传入set方法中

    <bean id="pDao" class="com.offcn.dao.PerDaoImpl">跳转到类中实现方法

    <property name="pid" value="11"></property>

    <property name="pname"><value>12</value></property>两种属性赋值方式

    </bean>

    3.(1)在PerDaoImpl中save方法中打印(测试)(PerDaoImpl类)

    public void save(){

    System.out.println("明天");

    }

    (2)主函数测试(App类)

    PerDao pd=(PerDao) ap.getBean("pDao");获取beans.xml文件中bean标签id为pDao,

    如(bean id="pDao") pd.save();

    其他类型的注入

    1.实体类中添加其他类型的属性及set,get方法

    private UserDaoImpl ud;

    private List<Object> list;

    public UserDaoImpl getUd() { return ud; }

    public void setUd(UserDaoImpl ud) {
      this.ud = ud;
    }

    public List<Object> getList() { return list; }

    public void setList(List<Object> list) {
      this.list = list;
    }

    2.在配置中赋值(beans.xml)

    为自定义类型赋值的方式:外部引入和内部引入两种方式

    <property name="ud"> 实体类中定义的属性名为ud

    <bean class="com.offcn.dao.UserDaoImpl"></bean>

    </property>

    list列表注入

    <property name="list"> 实体类中定义的属性名为list

    <list>

    <value>11</Value>

    <ref bean="uDao"></ref>

    <bean class="com.offcn.dao.UserDaoImpl"></bean>跳转到类中实现方法

    </list>

    </property>

    注:<bean id="uDao" class="com.offcn.dao.UserDaoImpl"></bean>

    list标签下后两条数据输出结果一致

    3.PerDaoImpl中的save方法打印(PerDaoImpl类)

    System.out.println("list:"); for (Object o : list) { property标签下list标签数据 System.out.println("list:"+o); }

    Spring注入方式之构造方法注入

    1.在实体类中加构造函数

    public PerDaoImpl(int pid, UserDaoImpl ud) { 有参构造方法 super(); this.pid = pid; this.ud = ud; }

    2.在配置文件中构造方法注入

    <bean id="pd" class="com.offcn.dao.PerDaoImpl">

    <constructor-arg index="0">

    <value>12</value>

    </constructor-arg>

    <constructor-arg index="1">

    <ref bean="uDao"></ref>

    -----<bean class="com.offcn.dao.UserDaoImpl"></bean>-----与其是两种表示方式

    </constructor-arg>

    </bean>

    3.(1)在PerDaoImpl中save方法中打印(测试)(PerDaoImpl类)

    public void save(){

    System.out.println("明天");

    }

    (2)主函数测试(App类)

    PerDao pd=(PerDao) ap.getBean("pd");获取beans.xml文件中bean标签id为pd,

    如(bean id="pDao")、其中(PerDao)是强制转换类型 pd.save();

     

  • 相关阅读:
    杭州电子科技大学程序设计竞赛(2016’12)- 网络同步赛 1001
    AtCoder Beginner Contest 050 ABC题
    2016年第四届湘潭大学新生趣味程序设计竞赛
    华东交通大学2016年ACM“双基”程序设计竞赛 1008
    移动端报表JS开发示例
    unity shader入门
    现代控制理论思考题----倒立摆小车控制算法研究
    Linux驱动基础:msm平台,modem等framework加载
    简谈高通Trustzone的实现
    现代控制理论课件分享及课后思考题(初稿待完善)
  • 原文地址:https://www.cnblogs.com/Hiramunderneath/p/14915499.html
Copyright © 2011-2022 走看看