【Spring】Spring框架入门案例

1.下载Spring5

(1)Spring官网 https://spring.io/
(2)下载地址https://repo.spring.io/ui/native/release/org/springframework/spring/

image

image

下载解压,文件夹说明
image

2.创建普通Java工程

image

导入Spring5相关jar包
image

spring5模块,至少需要核心部分,logging为额外需要的日志包
image

把这些jar包导入idea
image

image

3.使用Spring的方式创建对象

(1)新建类和方法

public class User {
    public void add(){
        System.out.println("add.......");
    }
}

(2)使用xml配置文件的方式,id表示别名,class为类全路径

<?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">

    <!--配置 User 对象创建-->
    <bean id="user" class="com.pxk.User"></bean>

</beans>

(3)获取配置文件中的对象

    @Test
    public void test(){
       //1.加载配置文件
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

        //2.获取对象
        User user = context.getBean("user",User.class);

        System.out.println(user);
        user.add();
    }

image

不同于传统的new User()的方式获取对象。

posted @ 2023-02-08 20:29  植树chen  阅读(16)  评论(0编辑  收藏  举报