Skip to content

一、基于XML方式搭建 Spring5 环境

1. 创建一个 maven 项目

  • 创建一个名为 hello-spring Maven 项目

2. 添加 spring-context 依赖

    • 通过依赖管理: 在 pom.xml 中添加,spring 核心依赖。
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>

    <groupId>com.calvin</groupId>
    <artifactId>hello-spring</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <!-- spring 上下文 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.15.RELEASE</version>
        </dependency>
    </dependencies>

</project>

3. 在 resources 中,创建 spring-context.xml 配置文件

xml
<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="userService" class="com.calvin.hello.spring.service.impl.UserServiceImpl"/>

</beans>

4. 创建 UserService.java 接口, 添加用户行为sayHi()方法。

java
package com.calvin.hello.spring.service;


/**
 * 用户服务
 *
 * @author calvin
 * @date 2023/02/15
 */
public interface UserService {

    /**
     * 打个招呼
     */
    void sayHi();
}

5. 创建 UserServiceImpl.java, 实现 UserService 接口下用户行为sayHi()方法。

java
package com.calvin.hello.spring.service.impl;

import com.calvin.hello.spring.service.UserService;

/**
 * @author Calvin
 * @date 2023/2/15
 * @since v1.0.0
 */
public class UserServiceImpl implements UserService {

    public void sayHi() {
        System.out.println("Hello Spring!");
    }
}

6. 创建一个 MyTest.java 启动类,通过IOC容器创建调用 User 对象

java
package com.calvin.hello.spring;

import com.calvin.hello.spring.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Calvin
 * @date 2023/2/15
 * @since v1.0.0
 */
public class MyTest {

    public static void main(String[] args) {
        /**
         * Ioc 控制反转: 通过调用Spring API, 获取对象,该对象交给Spring 容器进行托管,这就是控制反转。
         */

        // 1. 获取配置文件xml信息
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-context.xml");
        // 2. 从xml获取托管用户对象
        UserService userService = (UserService) applicationContext.getBean("userService");
        // 3. 对象行为
        userService.sayHi();
    }

}
log
# 输出结果
Hello Spring!

二、基于注解方式搭建 Spring5 环境

1. 创建一个 maven 项目

  • 创建一个名为 02-spring-quicks-start Maven 项目

2. 添加 spring-context 依赖

  • 在 pom.xml 中添加,spring 依赖
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>

    <groupId>org.example</groupId>
    <artifactId>01-spring-quicks-start</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
       <!-- spring 上下文 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.10.RELEASE</version>
        </dependency>

        <!-- Lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
    </dependencies>

</project>

3. 创建一个 User.java 类对象

java
package org.example.spring5.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

/**
 * @author: Calvin <br>
 * @date: 2020/11/25 10:29 <br>
 * @since: 1.0 <br>
 * @description: User <br>
 */
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class User {

    /** 用户ID */
    private Long userId;

    /** 用户名称 */
    private String userName;

    /** 年龄 */
    private Integer age;
}

4. 创建一个 SpringConfiguration.java 类, 这个相当于 application-context.xml 配置文件。

java
package org.example.spring5.config;

import org.example.spring5.domain.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: Calvin <br>
 * @date: 2020/11/25 14:18 <br>
 * @since: 1.0 <br>
 * @description: SpringConfig <br>
 */
// @Configuration 相当于 application-context.xml
@Configuration
public class SpringConfiguration {

    /**
     * 注解Bean 相当于 <bean></bean>标签
     * @return User
     */
    @Bean
    public User user(){
        return new User(1L, "Calvin", 26);
    }
}

5. 创建一个 SpringApplicaton.java 启动类,通过IOC容器创建调用 User 对象

java
package org.example.spring5;

import org.example.spring5.config.SpringConfiguration;
import org.example.spring5.domain.User;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author: Calvin <br>
 * @date: 2020/11/25 14:27 <br>
 * @since: 1.0 <br>
 * @description: SpringApplication <br>
 */
public class SpringApplication {

    // 基于注解的形式Spring 上下文
    private static AnnotationConfigApplicationContext annotationConfigApplicationContext;

    public static void main(String[] args) {
        // 获取上下文
        annotationConfigApplicationContext  = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        // 获取 Bean 对象
        User userBean = annotationConfigApplicationContext.getBean(User.class);
        // 打印 Bean 对象
        System.out.println(userBean);
    }
}
log
# 输出结果
User(userId=1, userName=Calvin, age=26)

三、扩展:怎么样将@Controller、@Service、@Repository、@Component 对象引入到配置文件中 ?

1. 创建 UseController.java 控制器类, 添加 @Controller 注入到Spring容器中。

java
package org.example.spring5.controller;

import org.springframework.stereotype.Controller;

/**
 * @author: Calvin <br>
 * @date: 2020/11/25 14:17 <br>
 * @since: 1.0 <br>
 * @description: UserController <br>
 */
@Controller
public class UserController {
}

2. 创建 UserDao.java 数据访问类,添加 @Repository 注入到Spring 容器中。

java
package org.example.spring5.dao;

import org.springframework.stereotype.Repository;

/**
 * @author: Calvin <br>
 * @date: 2020/11/25 14:17 <br>
 * @since: 1.0 <br>
 * @description: UserDao <br>
 */
@Repository
public class UserDao {
}

3. 创建 UserService.java 接口类、UserServiceImpl 实现类,添加 @Service 注入到Spring 容器中。

java
package org.example.spring5.service.impl;

import org.example.spring5.service.UserService;
import org.springframework.stereotype.Service;

/**
 * @author: Calvin <br>
 * @date: 2020/11/25 14:17 <br>
 * @since: 1.0 <br>
 * @description: UserService <br>
 */
@Service
public class UserServiceImpl implements UserService {
}

4. 通过 @ComponentScan 组件扫包形式,将它注入到 SpringConfig 配置类中。

  • 通过@ComponentScan 组件扫包 org.example.spring5 下,将标记有 @Service、 @Repository、 @Controller、 @Component 放入到该配置文件中。
java
package org.example.spring5.config;

import org.example.spring5.domain.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * @author: Calvin <br>
 * @date: 2020/11/25 14:18 <br>
 * @since: 1.0 <br>
 * @description: SpringConfig <br>
 */
@Configuration // @Configuration 相当于 application-context.xml
@ComponentScan(value = "org.example.spring5") // 通过扫包 org.example.spring5, 将标记有 @Service @Repository @Controller @Component 放入到该配置文件中。
public class SpringConfiguration {

    /**
     * 注解Bean 相当于 <bean></bean>标签
     * @return User
     */
    @Bean
    public User user(){
        return new User(1L, "Calvin", 26);
    }
}

5. 创建一个 SpringApplicaton.java 启动类,通过不同注解方式,创建和调用对象。

java
package org.example.spring5;

import org.example.spring5.config.SpringConfiguration;
import org.example.spring5.controller.UserController;
import org.example.spring5.dao.UserDao;
import org.example.spring5.domain.User;
import org.example.spring5.service.UserService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.Arrays;

/**
 * @author: Calvin <br>
 * @date: 2020/11/25 14:27 <br>
 * @since: 1.0 <br>
 * @description: SpringApplication <br>
 */
public class SpringApplication {

    private static AnnotationConfigApplicationContext annotationConfigApplicationContext;

    public static void main(String[] args) {
        annotationConfigApplicationContext  = new AnnotationConfigApplicationContext(SpringConfiguration.class);

        // @Bean 的方式创建和调用对象
        User userBean = annotationConfigApplicationContext.getBean(User.class);
        System.out.println(userBean);

        // @Controller 的方式创建和调用对象
        UserController userControllerBean = annotationConfigApplicationContext.getBean(UserController.class);
        System.out.println(userControllerBean);

        // @Repository 的方式创建和调用对象
        UserDao userDaoBean = annotationConfigApplicationContext.getBean(UserDao.class);
        System.out.println(userDaoBean);

        // @Service 的方式创建和调用对象
        UserService userServiceBean = annotationConfigApplicationContext.getBean(UserService.class);
        System.out.println(userServiceBean);

        // 获取已经在上下文Bean对象类名列表
        Arrays.stream(annotationConfigApplicationContext.getBeanDefinitionNames())
                .forEach(System.out::println);
    }
}
log
# 测试结果
User(userId=1, userName=Calvin, age=26)
org.example.spring5.controller.UserController@662b4c69
org.example.spring5.dao.UserDao@fa49800
org.example.spring5.service.impl.UserServiceImpl@71238fc2