JavaEE笔记(八)

第一个Spring

Student(学生) bean

package com.my.bean;

import java.io.Serializable;

public class Student implements Serializable{
    private static final long serialVersionUID = 1L;
    private String name;
    private MyClass myClass;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public MyClass getMyClass() {
        return myClass;
    }
    public void setMyClass(MyClass myClass) {
        this.myClass = myClass;
    }
    
}

Class(班级) bean

package com.my.bean;

import java.io.Serializable;

public class MyClass implements Serializable{
    private static final long serialVersionUID = 1L;
    private String name;

    public String getName() {
        return name;
    }

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

需要导入的jar包

beans配置文件

<?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.my.bean.Student">
<property name="name" value="小明"/>
<property name="myClass" ref="cls"/>
</bean>
<bean id="cls" class="com.my.bean.MyClass">
<property name="name" value="班级一"/>
</bean>
</beans>

获取已经配置的Student类

package com.my.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.my.bean.Student;

public class Test {
    /**
     * @param args
     */
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("beans.xml");
        //获取已经配置的Stu
        Student stu = context.getBean("stu",Student.class);
        System.err.println(stu.getName());
    }

}

我不作恶

但有权拒绝为善

我不赞同

但是我捍卫你不为善的权力

原文地址:https://www.cnblogs.com/HackerBlog/p/6135323.html