MyEclipse配置Spring框架(基礎篇)


一、新建項目,添加spring的相關jar包等

二、創建相關類以及屬性和方法

Student.java

package com.yh;

public class Student implements People {
    
    private Course course;
    @Override
    public void breath() {
        // TODO Auto-generated method stub
        System.out.println("呼吸");
    }
    public Course getCourse() {
        return course;
    }
    public void setCourse(Course course) {
        this.course = course;
    }

}

 

三、配置xml文件

自動裝配方法一:設置autowire(這里為byName)

<?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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
    
    <bean id="student" class="com.yh.Student" autowire="byName"></bean>
    
    <bean id="course" class="com.yh.Course"></bean>

</beans>

裝配方法:Student類的成員變量名對應bean的id。

自動裝配方法二:

<?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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">

    <bean id="student" class="com.yh.Student">
        <property name="course" ref="course"></property>
    </bean>
    
    <bean id="course" class="com.yh.Course"></bean>

</beans>

裝配方法:name對應Student類中名為course的成員變量,ref對應當前xml文件中id為course的bean。

 

四、編寫測試類

package com.yh;

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

public class SpringDemoTest {

    @Test
    public void demo01(){
        String xmlPath="applicationContext.xml";
        ApplicationContext context = new ClassPathXmlApplicationContext(xmlPath);
        Student stu = (Student)context.getBean("student");
        stu.breath();
        stu.getCourse().showCourse();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM