第一个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就绪,可使用
要点总结
- ApplicationContext是Spring的IoC容器
- XML方式使用ClassPathXmlApplicationContext加载配置
- Java配置使用AnnotationConfigApplicationContext
- Spring Boot通过@SpringBootApplication自动配置
- 通过context.getBean()获取容器中的Bean实例
📝 发现内容有误?点击此处直接编辑