Skip to content

入门案例

  1. 创建maven工程
  2. 引入pom依赖
xml
<?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.wyizd</groupId>
        <artifactId>spring6</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>spring-first</artifactId>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>6.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.3.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>
  1. 创建实体类
java
package com.wyizd;
public class User {
    public User() {
        System.out.println("证明无参构造执行了");
    }

    public void add(){
        System.out.println("user add ...");
    }
}
  1. 交由spring管理(bean.xml)
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标签,完成user对象的创建
    id:唯一标识
    class:对象所在类的全路径
    -->
    <bean id="user" class="com.wyizd.User">
    </bean>
</beans>
  1. 通过spring获取并使用
java
import com.wyizd.User;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestUser {
    @Test
    public void testUserObject(){
        //加载spring配置文件,创建对象
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        //获取创建的对象
        User user = (User) applicationContext.getBean("user");
        System.out.println(user);
        //测试对象的方法
        user.add();
    }
}
  1. 输出结果

证明无参构造执行了
com.wyizd.User@4ef37659
user add ...

Process finished with exit code 0
  1. 分析
    1. 构造方法调用了,但是spring没有使用new方法,所以应该是使用了反射机制
    2. spring通过org.springframework.context.support.ClassPathXmlApplicationContext读取bean.xml获取到了类信息,再通过org.springframework.beans.factory.config.BeanDefinition进行管理