使用spring注解实现自动装配

77 阅读1分钟

需求:通过注解的方式实现model层的自动装配。调用者通过配置来实现自动装配;

实现思路:使用application.yaml和 spring注解;

ConditionalOnProperty注解

@ConditionalOnProperty 是 Spring Boot 中的一个条件注解,它允许基于环境属性(environment properties)的值来控制某个配置类或者 bean 的创建。

  • name 或 value:用于指定要检查的属性的名称。
  • prefix:用于指定要检查的属性的前缀。
  • havingValue:用于指定要检查的属性的值。只有当指定的属性存在且其值等于 havingValue 指定的值时,条件才为真。
import org.springframework.context.annotation.ConditionalOnProperty;  
import org.springframework.stereotype.Component;  
  
@ConditionalOnProperty(prefix = "com.text", name="feature", havingValue="enabled")  
@Component  
public class FeatureA {  
    // 实现功能A的代码  
}

对应的yaml配置文件

com
  text
    feature: enabled

EnableConfigurationProperties

用于启用对特定配置属性类的支持。当你有一个类使用了 @ConfigurationProperties 注解来绑定配置文件中的属性时,你通常需要在某个配置类上使用 @EnableConfigurationProperties 来确保这个配置属性类被 Spring 容器加载并处理。

@Configuration  
@EnableConfigurationProperties(ModelConfigurationProperties.class)  
public class MyAppConfig {  
    // 其他配置...  
}


@Data  
@ConfigurationProperties(prefix = "com.models.test")  
public class ModelConfigurationProperties {  
private String url;  
}

在这个例子中,MyAppConfig 是一个配置类,它使用 @EnableConfigurationProperties 注解来启用 ModelConfigurationProperties 类的支持。这意味着 Spring Boot 会加载并处理 ModelConfigurationProperties 类,将其绑定到配置文件中的 com.models.test 前缀的属性上。