全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-18 6 分钟 ✍️ juanwangdev

第一个Spring 应用

创建一个最简单的Spring应用,演示Spring的核心工作流程。

方式一:传统Spring

1. 定义Service

Java
package com.example.service;

public class UserService {
    public String sayHello(String name) {
        return "Hello, " + name + "!";
    }
}

2. 配置Bean(XML方式)

XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans">
    <bean id="userService" class="com.example.service.UserService"/>
</beans>

3. 启动应用

Java
public class Main {
    public static void main(String[] args) {
        // 加载配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        // 获取Bean
        UserService userService = context.getBean(UserService.class);

        // 调用方法
        System.out.println(userService.sayHello("Spring"));
    }
}

方式二:Spring Boot

1. 创建启动类

Java
package com.example;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

2. 定义Service

Java
package com.example.service;

@Service
public class UserService {
    public String sayHello(String name) {
        return "Hello, " + name + "!";
    }
}

3. 定义Controller

Java
package com.example.controller;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/hello")
    public String hello(@RequestParam String name) {
        return userService.sayHello(name);
    }
}

4. 启动测试

Bash
# 启动应用
mvn spring-boot:run

# 测试接口
curl http://localhost:8080/hello?name=Spring
# 输出:Hello, Spring!

方式三:纯Java配置

1. 配置类

Java
@Configuration
public class AppConfig {

    @Bean
    public UserService userService() {
        return new UserService();
    }
}

2. 启动类

Java
public class Main {
    public static void main(String[] args) {
        // 使用Java配置
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

        UserService userService = context.getBean(UserService.class);
        System.out.println(userService.sayHello("Spring"));
    }
}

三种方式对比

方式配置方式适用场景
XML配置applicationContext.xml传统项目、遗留系统
Java配置@Configuration新项目、类型安全
Spring Boot自动配置微服务、快速开发

应用启动流程

text
1. 加载配置(XML/Java注解)
       ↓
2. 创建IoC容器(ApplicationContext)
       ↓
3. 解析Bean定义
       ↓
4. 实例化并注入依赖
       ↓
5. Bean就绪,可使用

要点总结

  1. ApplicationContext是Spring的IoC容器
  2. XML方式使用ClassPathXmlApplicationContext加载配置
  3. Java配置使用AnnotationConfigApplicationContext
  4. Spring Boot通过@SpringBootApplication自动配置
  5. 通过context.getBean()获取容器中的Bean实例

📝 发现内容有误?点击此处直接编辑

← 上一篇 Spring 环境搭建与项目结构
下一篇 → Bean生命周期
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库