Spring基础小实例

来源:互联网 发布:手机淘宝字体放大 编辑:程序博客网 时间:2024/06/04 21:38

Student.java

package com.lovo.bean;public class Student {private String name;private MyClass cls;public MyClass getCls() {return cls;}public void setCls(MyClass cls) {this.cls = cls;}public String getName() {return name;}public void setName(String name) {this.name = name;}public void sayHi(){System.out.println("hi,"+this.getName());}}
MyClass

package com.lovo.bean;public class MyClass {private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}}

beans.xml

<?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 id="stu" class="com.lovo.bean.Student"><property name="name"><value>小明</value></property><property name="cls" ref="cla"></property></bean><bean id="cla" class="com.lovo.bean.MyClass"><property name="name" value="班级一"></property></bean></beans>
test测试

package com.lovo.test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.lovo.bean.Student;public class Test {public static void main(String[] args) {ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");Student stu = (Student) ac.getBean("stu");System.out.println(stu.getCls().getName());stu.sayHi();}}


0 0