SSM(2)-spring5-依赖注入与自动装配-autowired-实例源码

demo下载地址:https://download.csdn.net/download/aggie4628/12673642

1.依赖注入
   1.1构造器注入      对应:c命名空间
   1.2 set 注入          对应:P命名空间
         依赖:bean对象的创建依赖于容器。
         注入:bean对象中的所有属性由容器注入。
2.自动装配


1.依赖注入
   1.1构造器注入      对应:c命名空间
   1.2 set 注入          对应:P命名空间
         依赖:bean对象的创建依赖于容器。
         注入:bean对象中的所有属性由容器注入。

如果出现以下:


2.自动装配,环境搭建:demo
 2.1 3个DAO类 :Person,Dog,Cat



 2.2 beans-person.xml
       参数:byname 是变量名
       参数:byType 是类名
     bean中 id = 对应 类中的变量名
    <property name="”> 对应 类中的属性名 (Person name)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="cat" class="com.tang.Cat"/>
    <bean id="dog" class="com.tang.Dog" />
    <bean id="person" class="com.tang.Person" scope="singleton" autowire="byName">
        <property name="name" value="2"></property>
    </bean>


    <bean id="user" class="com.tang.User"  >

    </bean>

</beans>

 
 2.3 测试类
 

public class myTest {

    @Test
    void myTest1()
    {
        ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-person.xml");
        Person p =(Person) ctx.getBean("person",Person.class);//前面是变量  后面是类名
        p.getDog().bark();
        p.getCat().bark();
      //  System.out.println(p.getUserDAO());


    }


}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值