// Spring框架搭建示例代码
// 1. 引入依赖(Maven配置)
// 在pom.xml文件中添加Spring框架的依赖:
<dependencies>
<!-- Spring Core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.20</version>
</dependency>
<!-- Spring Context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.20</version>
</dependency>
<!-- Spring Web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.20</version>
</dependency>
<!-- Spring Boot Starter (如果使用Spring Boot) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.6.8</version>
</dependency>
</dependencies>
// 2. 创建Spring配置类
// 使用@Configuration注解来定义一个Spring配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
// 3. 创建服务接口和服务实现类
// 定义一个简单的服务接口和实现类
public interface MyService {
void performTask();
}
public class MyServiceImpl implements MyService {
@Override
public void performTask() {
System.out.println("Performing task...");
}
}
// 4. 创建主应用程序类并启动Spring容器
// 使用SpringApplication.run()来启动Spring Boot应用程序
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(Application.class, args);
// 获取bean并调用方法
MyService myService = context.getBean(MyService.class);
myService.performTask();
}
}
引入依赖:在pom.xml文件中添加了Spring框架的核心依赖,包括spring-core、spring-context和spring-web。如果你使用的是Spring Boot,则还需要添加spring-boot-starter依赖。
创建Spring配置类:使用@Configuration注解定义了一个Spring配置类AppConfig,并在其中通过@Bean注解定义了一个名为myService的bean。
创建服务接口和服务实现类:定义了一个简单的服务接口MyService和它的实现类MyServiceImpl。MyServiceImpl实现了performTask()方法。
创建主应用程序类并启动Spring容器:使用SpringApplication.run()启动Spring Boot应用程序,并通过ApplicationContext获取bean实例并调用其方法。
以上代码展示了如何使用Spring框架搭建一个简单的应用程序。
上一篇:java for 循环
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站