spring笔记

配置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
           http://www.springframework.org/schema/beans/spring-beans.xsd">


     
  <!-- 给bean对象取个别名 -->   
 <alias name="stu" alias="testStu"/>        
 


<!-- IOC 控制反转   ==  DI 依赖注入    -->
<!-- Student stu = new Student();  -->
<bean id="stu" class="com.my.bean.Student" >
<!--stu.setName()-->
<property name="name"  value="小明" />
<!-- 注入一个班级 -->
<property name="cls"  ref="myclass" />
<property name="age" value="13" />


</bean>


<bean id="myclass" class="com.my.bean.MyClass">
<!--name 对应的是类里面的属性名   -->
<property name="name" value="班级一"></property>
</bean>

测试bean写法:

public class Test {

public static void main(String[] args) {


/* Student stu = new Student();
stu.setName("小明");
stu.sayHi();*/

//实例化spring 容器
//IOC  
ApplicationContext ac = new ClassPathXmlApplicationContext("com/config/beans.xml");

//System.out.println(ac);
 Student stu = (Student) ac.getBean("testStu");
   //  stu.sayHi();
//Student stu = (Student) ac.getBean("stu");

//System.out.println("学生名:"+stu.getName() +"  班级:" +stu.getCls().getName()+" age:"+stu.getAge());


//第二种实例化spring 容器
//BeanFactory factory = new XmlBeanFactory(new ClassPathResource("com/config/beans.xml"));


//Student stu = (Student) factory.getBean("stu") ;
//System.out.println(stu.getName());


Emp emp = (Emp) ac.getBean("emp");
System.out.println(emp.getName()+"      "+emp.getDept().getName());

}


}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值