【Spring学习笔记】1.入门

1.依赖

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.1.6.RELEASE</version>
    </dependency>

添加spring-context即可,因为一旦添加,其他的会自动导入。

2 配置文件
在这里插入图片描述
applicationContext.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">

    <!--将对象的创建交给spring容器,在这个配置文件里去声明我要什么对象
    class :写Java类的全限定类名,它是通过全类名使用反射来创建
    id :   ID就是给这个对象在整个应用程序上下文当中取个名字以方便区分

    -->

    <bean class="com.cyk.pojo.Girl" id="girl">
    </bean>

</beans>

Girl.java

package com.cyk.pojo;

public class Girl {

    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

测试类

@Test
    public void m1(){

        //1.获取上下文对象,spring里面声明对象都需要通过上下文对象获取
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        //2.通过这个对象获取这个girl
        Girl g = (Girl) ctx.getBean("girl");
        System.out.println(g);

    }

猜你喜欢

转载自blog.csdn.net/weixin_43046082/article/details/88982791