石家庄停车位在线预约平台07
下面是创建好的项目结构,我创建了bean包,测试类、和配置文件
idea可以自动生成是Spring的配置文件 步骤是在需要生成配置文件的目录上鼠标右键--》New--》XML Configuration File--》Spring Config--》然后起文件名点击Finish
下面是写好的测试 Person类
package com.spring.bean; /** * @Author: 007 * @Date: 2019/1/27/0027 10:20 * @Version 1.0 * @Description: 创建测试用的bean */ public class Person { private String name; //姓名 private int age; //年龄 public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
配置Spring的核心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:给配置的类起个后续在容器中获取用的id class:类所在的路径 --> <bean id="Person" class="com.spring.bean.Person"/> </beans>
在程序中读取Spring的配置文件来获取Bean(Bean其实就是一个new好的对象)
package com.spring.test; import com.spring.bean.Person; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @Author: 007 * @Date: 2019/1/27/0027 10:21 * @Version 1.0 * @Description: */ public class Test { public static void main(String[] args) { //查询类路径 加载配置文件 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); //根据id获取bean //Spring就是一个大工厂(容器)专门生成bean bean就是对象 Person person = (Person) applicationContext.getBean("Person"); //输出获取到的对象 System.out.println("person = " + person); } }
至此入门案例编写完成。
posted on 2020-02-07 19:53 xiaohaigege666 阅读(107) 评论(0) 收藏 举报