MyEclipse配置Spring框架(基础篇)

该博客介绍Java Spring项目搭建过程。首先新建项目并添加Spring相关jar包,接着创建相关类及属性方法,如Student.java。然后配置xml文件,介绍两种自动装配方法。最后编写测试类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、新建项目,添加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();
    }

}

 

转载于:https://www.cnblogs.com/YeHuan/p/11071915.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值