Spring核心注解详解(一)

1、@Configuration

此注解是 Spring Framework 中用于标识配置类的注解。被 @Configuration 注解标记的类通常包含了一系列用于配置 Spring 容器的 Bean,可以替代传统的 XML 配置文件。

基本用法:

@Configuration
public class AppConfig {
    
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
    
    // 其他配置方法
}

在上述例子中,AppConfig 类被标注为 @Configuration,表示它是一个配置类。myBean 方法使用 @Bean 注解声明了一个 Bean,并返回一个 MyBean 类型的实例。这个 Bean 将会被 Spring 容器管理。

与@ComponentScan结合使用:

@Configuration
@ComponentScan("com.example")
public class AppConfig {
    
    // 其他配置方法
}

在上述例子中,@ComponentScan 用于启用组件扫描,指定要扫描的包路径,Spring 将自动扫描指定包及其子包中的组件,并注册为 Spring 容器中的 Bean。

与@Import结合使用:

@Configuration
@Import({DatabaseConfig.class, ServiceConfig.class})
public class AppConfig {
    
    // 其他配置方法
}

在上述例子中,@Import 注解用于引入其他配置类,即 DatabaseConfig 和 ServiceConfig。这样,AppConfig 中就可以使用这两个配置类中声明的 Bean。

使用外部属性配置:

@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
    
    @Value("${my.property}")
    private String myProperty;

    @Bean
    public MyBean myBean() {
        // 使用myProperty配置Bean
        return new MyBean(myProperty);
    }
    
    // 其他配置方法
}

在上述例子中,通过 @PropertySource 注解引入外部属性文件(例如 application.properties),并使用 @Value 注解注入属性值。

注意事项:

@Configuration 注解通常用在类级别上,用于标识一个类为 Spring 的配置类。

被 @Configuration 注解标记的类通常包含用于配置 Spring 容器的方法,这些方法使用 @Bean 注解声明要注册到容器的 Bean。

@ComponentScan 注解通常与 @Configuration 一起使用,用于启用组件扫描,自动注册组件为 Bean。

@Import 注解通常与 @Configuration 一起使用,用于引入其他配置类,方便配置的模块化。

@PropertySource 注解通常与 @Configuration 一起使用,用于引入外部的属性配置文件。

2、@ComponentScan

此注解
是 Spring Framework 中用于扫描并加载标有 @Component 及其衍生注解的类的注解。通过 @ComponentScan 注解,Spring 可以自动扫描指定的包路径下的组件,并将其注册为 Spring 容器中的 Bean。

基本用法:

@Configuration
@ComponentScan("com.example")
public class AppConfig {
    // 其他配置
}

在上述例子中,@ComponentScan(“com.example”) 表示 Spring 将扫描 com.example 包及其子包中的所有组件,并将其注册为 Spring 容器中的 Bean。

包扫描的其他用法:

@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
    // 其他配置
}
@Configuration
@ComponentScan(basePackages = {"com.example", "com.anotherexample"})
public class AppConfig {
    // 其他配置
}
@Configuration
@ComponentScan(basePackageClasses = {MyComponent.class, AnotherComponent.class})
public class AppConfig {
    // 其他配置
}

在上述例子中,basePackages 属性用于指定要扫描的基础包,可以传递多个包路径。而 basePackageClasses 属性则可以通过指定类的方式来指定要扫描的基础包,通常用于指定某个包下的特定类。

排除特定的组件:

@Configuration
@ComponentScan(basePackages = "com.example", excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = ".*Exclude.*"))
public class AppConfig {
    // 其他配置
}

在上述例子中,excludeFilters 属性用于指定要排除的组件。在这个例子中,通过正则表达式排除了所有包含 “Exclude” 的组件。

指定扫描的类和接口:

@Configuration
@ComponentScan(basePackageClasses = MyComponent.class, includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = AnotherComponent.class))
public class AppConfig {
    // 其他配置
}

在上述例子中,includeFilters 属性用于指定要包括的组件,通过 FilterType.ASSIGNABLE_TYPE 指定了只包括 AnotherComponent 类。

指定扫描的注解:

@Configuration
@ComponentScan(basePackages = "com.example", includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = MyCustomAnnotation.class))
public class AppConfig {
    // 其他配置
}

在上述例子中,includeFilters 属性用于指定要包括的组件,通过 FilterType.ANNOTATION 指定了只包括标有 MyCustomAnnotation 注解的组件。

注意事项:

@ComponentScan 注解通常用在配置类上,用于指定要扫描的包路径。

扫描到的组件将被注册为 Spring 容器中的 Bean,可以通过 @Autowired 注解进行注入。

@ComponentScan 可以配合其他注解使用,例如 @Configuration、@Component、@Service、@Repository 等。

如果使用 Spring Boot,通常不需要显式配置 @ComponentScan,因为 Spring Boot 默认会扫描主应用类所在的包及其子包。

3、@Bean

此注解是 Spring Framework 中用于声明一个 Bean 的注解。被 @Bean 注解标记的方法通常用于生产并配置一个特定类型的 Bean,并将其注册到 Spring 容器中。这种方式可以替代传统的 XML 配置文件。

基本用法:

@Configuration
public class AppConfig {

    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
    
    // 其他配置方法
}

在上述例子中,myBean 方法使用 @Bean 注解声明了一个 Bean,并返回一个 MyBean 类型的实例。这个 Bean 将会被 Spring 容器管理。

使用外部属性配置:

@Configuration
public class AppConfig {

    @Value("${my.property}")
    private String myProperty;

    @Bean
    public MyBean myBean() {
        // 使用myProperty配置Bean
        return new MyBean(myProperty);
    }
    
    // 其他配置方法
}

在上述例子中,通过 @Value 注解注入外部属性值,并在 myBean 方法中使用这个属性值进行 Bean 的配置。

通过参数传递依赖 Bean:

@Configuration
public class AppConfig {

    @Bean
    public MyDependency myDependency() {
        return new MyDependency();
    }

    @Bean
    public MyBean myBean(MyDependency myDependency) {
        return new MyBean(myDependency);
    }
    
    // 其他配置方法
}

在上述例子中,myBean 方法接收一个 MyDependency 类型的参数,并通过参数传递将其注入到 myBean 方法中。

使用初始化和销毁方法:

@Configuration
public class AppConfig {

    @Bean(initMethod = "init", destroyMethod = "cleanup")
    public MyBean myBean() {
        return new MyBean();
    }
    
    // 其他配置方法
}

在上述例子中,通过 initMethod 和 destroyMethod 属性分别指定了 Bean 的初始化方法和销毁方法。这些方法将在 Bean 的生命周期中被调用。

注意事项:

@Bean 注解通常用在方法级别上,用于声明一个 Bean。

被 @Bean 注解标记的方法通常返回一个对象实例,该对象将被 Spring 容器管理。

@Bean 注解通常与 @Configuration 注解一起使用,用于声明配置类中的 Bean。

@Bean 注解可以接收参数,这些参数可以是其他的 Bean,Spring 将负责解析和注入这些依赖。

@Bean 注解还可以指定初始化方法和销毁方法,通过 initMethod 和 destroyMethod 属性。

在 Spring Boot 应用中,通常不需要显式配置 @Bean,因为 Spring Boot 提供了自动配置的功能,会自动注册符合条件的 Bean。

4、@Scope

此注解是 Spring Framework 中用于指定 Bean 的作用域的注解。通过 @Scope 注解,可以控制 Spring 容器如何创建和管理 Bean 的实例。Spring 支持多种作用域,包括单例(Singleton)、原型(Prototype)、会话(Session)、请求(Request)等。

基本用法:

@Component
@Scope("singleton")
public class MySingletonBean {
    // 类的实现
}

在上述例子中,MySingletonBean 类被标注为 @Component,并使用 @Scope(“singleton”) 注解指定了该 Bean 的作用域为单例(Singleton)。这表示在整个 Spring 容器中,只会存在一个 MySingletonBean 的实例。

原型作用域(Prototype):

@Component
@Scope("prototype")
public class MyPrototypeBean {
    // 类的实现
}

在上述例子中,MyPrototypeBean 类的作用域被指定为原型(Prototype)。这表示每次通过 Spring 容器获取 MyPrototypeBean 的实例时,都会创建一个新的实例。

会话作用域(Session):

@Component
@Scope("session")
public class MySessionBean {
    // 类的实现
}

在上述例子中,MySessionBean 类的作用域被指定为会话(Session)。这表示每个用户会话(例如在 Web 应用中的用户会话)都会有一个独立的 MySessionBean 实例。

请求作用域(Request):

@Component
@Scope("request")
public class MyRequestBean {
    // 类的实现
}

在上述例子中,MyRequestBean 类的作用域被指定为请求(Request)。这表示每个 HTTP 请求都会有一个独立的 MyRequestBean 实例。

使用 @RequestScope、@SessionScope、@ApplicationScope:

除了直接使用 @Scope 注解,Spring 还提供了更具体的作用域注解,分别是 @RequestScope、@SessionScope 和 @ApplicationScope,用于表示请求、会话和应用作用域。

@Component
@RequestScope
public class MyRequestScopedBean {
    // 类的实现
}
@Component
@SessionScope
public class MySessionScopedBean {
    // 类的实现
}
@Component
@ApplicationScope
public class MyApplicationScopedBean {
    // 类的实现
}

这些注解与使用 @Scope 注解指定作用域的效果是一样的,只是更为直观和语义化。

注意事项:

默认情况下,Spring Bean 的作用域是单例(Singleton)。

使用 @Scope 注解时,需要指定作用域的名称,如 "singleton"、"prototype"、"session"、"request" 等。

作用域为原型(Prototype)的 Bean 在每次请求时都会创建一个新的实例。

作用域为会话(Session)的 Bean 在每个用户会话中都会有一个独立的实例。

作用域为请求(Request)的 Bean 在每次 HTTP 请求时都会创建一个独立的实例。

在 Web 应用中,@RequestScope、@SessionScope 和 @ApplicationScope 注解更为常用,用于表示特定的 Web 作用域。

5、@Qualifier

此注解是 Spring 框架中用于指定在存在多个相同类型的 bean 时,通过限定符选择特定 bean 的注解。通常与 @Autowired 或 @Resource 一起使用,以解决自动装配时的歧义问题。

属性:
@Qualifier 注解的主要属性是 value,用于指定要注入的 bean 的名称。该属性的值是一个字符串,对应于目标 bean 的名称。

示例:

public interface MyService {
    void doSomething();
}

@Service("serviceA")
public class ServiceA implements MyService {
    @Override
    public void doSomething() {
        System.out.println("ServiceA is doing something.");
    }
}

@Service("serviceB")
public class ServiceB implements MyService {
    @Override
    public void doSomething() {
        System.out.println("ServiceB is doing something.");
    }
}

@Component
public class MyComponent {
    @Autowired
    @Qualifier("serviceA")
    private MyService myService;

    // other methods
}

在上面的例子中,MyComponent 类中使用了 @Autowired 和 @Qualifier 注解,指定了要注入的 MyService bean 的名称是 “serviceA”。这样就明确了要注入的是哪个实现了 MyService 接口的 bean。

6、@Primary

此注解是 Spring Framework 中用于标识首选(Primary)Bean的注解。当一个接口或类有多个实现类或多个 Bean 符合某个类型时,通过 @Primary 注解可以指定其中一个作为首选的 Bean。

基本用法:

@Component
@Primary
public class PrimaryBean1 implements MyInterface {
    // 类的实现
}

在上述例子中,PrimaryBean1 类实现了 MyInterface 接口,并使用 @Primary 注解标识为首选的 Bean。

@Component
public class PrimaryBean2 implements MyInterface {
    // 类的实现
}

在上述例子中,PrimaryBean2 类也实现了 MyInterface 接口,但没有使用 @Primary 注解。

与@Autowired一起使用:

@Component
public class MyComponent {

    @Autowired
    private MyInterface myInterface;

    // 其他类的实现
}

在上述例子中,MyComponent 类通过 @Autowired 注解注入了一个实现了 MyInterface 接口的 Bean。由于 PrimaryBean1 使用了 @Primary 注解,它会被作为首选的 Bean 注入到 myInterface 字段中。

注意事项:

@Primary 注解通常用在类级别上,用于标识一个类为首选的 Bean。

当一个接口或类有多个实现类或多个 Bean 符合某个类型时,使用 @Primary 注解可以指定其中一个作为首选的 Bean。

如果有多个 Bean 符合某个类型,并且没有使用 @Primary 注解,Spring 将抛出 NoUniqueBeanDefinitionException 异常。

@Primary 注解可以与 @Qualifier 注解一起使用,以便更精确地选择首选 Bean。
@Component
@Primary
@Qualifier("myQualifier")
public class PrimaryBean1 implements MyInterface {
    // 类的实现
}
@Component
@Qualifier("myQualifier")
public class PrimaryBean2 implements MyInterface {
    // 类的实现
}

在上述例子中,通过 @Qualifier(“myQualifier”) 注解指定了一个限定符,使得 PrimaryBean1 在限定符的条件下成为首选的 Bean。

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

户伟伟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值