首页 > 编程语言 > 详细

Spring第一个实例

时间:2021-08-11 15:30:08      阅读:7      评论:0      收藏:0      [点我收藏+]

  首先创建一个Person类

public class Person {
    private String name;

    public Person() {
    }

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Person{" +
                "name=‘" + name + ‘\‘‘ +
                ‘}‘;
    }
}

  然后在resources目录下创建一个beans.xml文件

    这是官网文档地址

https://docs.spring.io/spring-framework/docs/5.2.0.RELEASE/spring-framework-reference/index.html

  beans.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="Person" class="Person">
        <property name="name" value="你好"/>
    </bean>
</beans>

    这个文件相当于执行了 Person person=new Person();

    然后又执行了 person.setName="你好";

  

  然后我们再创建一个MyTest测试类

ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

 

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

public class MyTest {
    @Test
    public void PersonTest() {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Object person = context.getBean("Person");
        System.out.println(person);
    }
}

  

  测试结果

技术分享图片

 

Spring第一个实例

原文:https://www.cnblogs.com/Sum-muji/p/15127982.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!