1. 首页
  2. 软件开发
  3. Spring——自定义注解和元注解汇总

Spring——自定义注解和元注解汇总

  • 发布于 2024-08-17
  • 0 次阅读

Spring中的自定义注解和元注解是用来帮助开发者简化配置和提高代码的可读性的。

  1. @Component :这是一个用来标识类为Spring组件的注解,Spring会自动扫描并注册这些组件。
  2. @Autowired :用来自动装配Spring Bean的注解,可以在属性、构造函数、方法上使用。
  3. @Qualifier :结合@Autowired一起使用,指定注入的Bean的名称。
  4. @Configuration :标识一个类为配置类,相当于Spring的XML配置文件。
  5. @Bean :在@Configuration类中使用,用来声明一个Bean。
  6. @Value :用来注入外部配置文件中的值。
  7. @ComponentScan :用来指定Spring在哪些包下寻找组件。

代码如下:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
   

    @Bean
    public MyService myService() {
   
        return new MyService();
    }
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MyComponent {
   

    private MyService myService;

    @Autowired
    public MyComponent(MyService myService) {
   
        this.myService = myService;
    }

}
import org.springframework.stereotype.Service;

@Service
public class MyService {
   

    // Service methods
}

原文链接: https://blog.csdn.net/2401_82884096/article/details/137940392