Idea创建Spring项目学习IoC

1 篇文章 0 订阅

1. 新建一个Spring项目

我将其命名为SpringIoC

2. 右键src,新建一个Spring的配置文件,命名为applicationContext.xml,暂时不进行配置

3. 在src下新建一个entity包,一个test包;entity包中包含实体类Student,test包中包含测试会用到的类TestStudent。文件目录如下:

下面给出Student.java以及TestStudent.java的代码

Student..java

public class Student {
    private String stuNo;
    private String stuName;
    //省略getter and setter
    //省略toString()
}

TestStudent.java

public class TestStudent {
    public static void main(String[] args) {
        //创建Spring的IoC容器对象
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        try{
            Student student = (Student) applicationContext.getBean("student");
            System.out.println(student.toString());
        }catch (NoSuchBeanDefinitionException e)
        {
            System.out.println(e.getMessage());
            System.out.println(e.getBeanName() + "不存在,请检查配置文件");
        }
    }
}

在applicationContext.xml中配置Bean

<?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="student" class="entity.Student">
        <property name="stuNo" value="2016211210069"></property>
        <property name="stuName" value="iwaed"></property>
    </bean>
</beans>

运行,结果如下:

done.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值