springboot纯注解
时间: 2025-01-17 15:52:39 浏览: 35
### 使用纯注解配置构建 Spring Boot 应用
#### 创建主应用程序类
在 Spring Boot 中,可以通过 `@SpringBootApplication` 注解来简化应用入口的创建。此注解是一个组合注解,它包含了 `@Configuration`, `@EnableAutoConfiguration` 和 `@ComponentScan` 功能[^3]。
```java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
#### 定义服务组件
为了展示如何利用纯注解的方式定义业务逻辑层的服务组件,在项目里可以创建一个简单的 Service 类并使用 `@Service` 进行标注:
```java
package com.example.demo.service;
import org.springframework.stereotype.Service;
@Service
public class MyServiceImpl implements MyService {
@Override
public String performTask() {
return "Task performed successfully!";
}
}
```
这里假设存在接口 `MyService` 及其具体实现 `MyServiceImpl`。
#### 编写控制器处理 HTTP 请求
接下来编写 RESTful API 控制器来接收外部请求并将任务委派给相应的服务对象执行:
```java
package com.example.demo.controller;
import com.example.demo.service.MyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TaskController {
private final MyService myService;
@Autowired
public TaskController(MyService myService) {
this.myService = myService;
}
@GetMapping("/perform-task")
public String performTask() {
return myService.performTask();
}
}
```
上述代码片段展示了如何通过构造函数注入依赖项 `myService` 并将其应用于处理器方法中[^1]。
#### 自定义配置类 (可选)
如果需要自定义某些 Bean 或者其他设置,则可以在单独的 Java 文件内声明带有 `@Configuration` 的类,并在里面注册所需的 Beans:
```java
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public MyCustomBean customBean() {
return new MyCustomBeanImpl();
}
}
```
这段代码说明了怎样借助于 `@Configuration` 和 `@Bean` 来代替传统的 XML 形式的 bean 定义文件[^2][^4]。
阅读全文
相关推荐


















