写一个简单的bean

bean1.java

package bean;

public class bean1 {
String name="123123";

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

@Override
public String toString() {
    return "bean1 [name=" + name + "]";
}

}

bean2.java

package bean;

public class bean2 {
    String name="0";
public void setBean1(bean1 bean1){
    System.out.println(bean1);
    this.name=bean1.getName();
}
@Override
public String toString() {
    return "bean2 [name=" + name + "]";
}

}

ApplicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    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-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">


    
<bean name="bean1" class="bean.bean1"></bean>
    <bean name="bean2" class="bean.bean2">
    <property name="bean1" ref="bean1"></property>
    </bean>
    
    
</beans>

测试方法:

1 public void testBean(){
2     ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
3 //    System.out.println("ac:"+ac);
4     Object bean=ac.getBean("bean2");
5     System.out.println("bean2:"+bean);
6 }

 

posted on 2019-11-11 16:44  withbear  阅读(224)  评论(0编辑  收藏  举报

导航