一、实验目标
理解注解方式与xml配置的区别,以及注解如何简化开发;掌握基础的注解开发方法。
二、实验内容
1、采用纯注解开发方式,实现自定义类的自动装配与管理(要求用@Component);
2、实现任意一个第三方bean的加载与管理(要求用@bean);
三、实验步骤
1.创建新的 Spring Boot 项目。
-
打开 IntelliJ IDEA。
-
点击 File -> New -> Project...。
-
选择 Spring boot,然后type选择maven,点击 Next。
-
勾选以下依赖项:
Spring Web -
点击 Next,然后点击 Finish。
2.添加自定义类及其 @Component 注解。
在 src/main/java/com/example/demo
路径下,创建一个名为 MyService.java
的新文件:
package com.example.demo;
import org.springframework.stereotype.Component;
@Component
public class MyService {
public String serve() {
return "Service is running.";
}
}
3.添加第三方 Bean 及其 @Bean 注解
在同一目录下,创建一个名为 AppConfig.java
的新文件:
package com.example.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Random;
@Configuration
public class AppConfig {
@Bean
public Random random() {
return new Random();
}
}
4.主应用程序类
打开 DemoApplication.java
:
package com.example.demo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.Random;
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
private final MyService myService;
private final Random random;
public DemoApplication(MyService myService, Random random) {
this.myService = myService;
this.random = random;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
System.out.println(myService.serve());
System.out.println("Random number: " + random.nextInt(100));
}
}
5.运行应用
结果展示:
6.理解 @Component 和 @Bean 的关系
-
@Component:
-
用于标识自定义类,使得 Spring 能够自动扫描并管理该类的实例。在开发中常用于服务、控制器等组件快速注册。
-
-
@Bean:
-
用于显式地定义和管理 Bean。这适用于第三方库中某些类或需要进行特殊构造的 Bean,并允许开发者配置 Bean 的初始化过程。
-
在实际应用场景中,当你需要快速创建和注入简单的服务或组件时,使用 @Component
是最便捷的方式。而在面对特定项(如需要传入构造参数或无法通过包扫描创建的外部类)时,@Bean
提供了更高的灵活性。
四、问题总结与体会
在这个实验中,遇到问题如下:
1.对于@Component 和 @Bean不熟悉。
2.对于spring boot的使用不熟悉。
以上问题2已解决,问题1有待加强。
通过这次实验令我收获了很多,了解了注解如何简化开发,并掌握基础的注解开发方法。