泰安企业建站公司淘宝关键词搜索量查询工具
@EnableConfigurationProperties && @ConfigurationProperties的使用时机
今天在写properties时想到了这个问题,为什么有时候我需要写
@EnableConfigurationProperties有时候又不需要呢?下面就详细讲讲。
@Data
@Component
@ConfigurationProperties(prefix = "hm.auth")
public class AuthProperties {private List<String> includePaths;private List<String> excludePaths;
}@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {private final AuthProperties authProperties;private final JwtTool jwtTool;private final AntPathMatcher antPathMatcher = new AntPathMatcher();
可以看到
AuthGlobalFilter并没有添加@EnableConfigurationProperties,只是简单的注入就可以使用。
@Data
@ConfigurationProperties(prefix = "hm.jwt")
public class JwtProperties {private Resource location;private String password;private String alias;private Duration tokenTTL = Duration.ofMinutes(10);
}@Configuration
@EnableConfigurationProperties(JwtProperties.class)
public class SecurityConfig {@Beanpublic PasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();}@Beanpublic KeyPair keyPair(JwtProperties properties){// 获取秘钥工厂KeyStoreKeyFactory keyStoreKeyFactory =new KeyStoreKeyFactory(properties.getLocation(),properties.getPassword().toCharArray());//读取钥匙对return keyStoreKeyFactory.getKeyPair(properties.getAlias(),properties.getPassword().toCharArray());}
}
可以看到
JwtProperties没有添加@Component注解,也就是没有注册为 Spring 容器中的 bean。然后SecurityConfig中就添加了@EnableConfigurationProperties(JwtProperties.class)然后在下面方法中通过参数自动注入public KeyPair keyPair(JwtProperties properties)。
为什么需要 @EnableConfigurationProperties?
- 默认情况下,使用
@ConfigurationProperties标注的类不会被自动注册为 Spring 容器中的 bean。 - 使用
@EnableConfigurationProperties(SecurityConfigProperties.class)会将该类注册为一个 Spring 管理的 bean,使它能够被自动注入。
因为前面
JwtProperties没有添加@Component注解,所以需要添加@EnableConfigurationProperties。而AuthProperties有@Component注解,也就是已经被spring管理了,所以不需要额外添加。
简化方式: 如果 SecurityConfigProperties 类本身已经用 @Component 标注,则无需额外使用 @EnableConfigurationProperties。
示例:
@Component
@ConfigurationProperties(prefix = "security")
public class SecurityConfigProperties {// 属性和 Getter/Setter 同前
}
在这种情况下,@EnableConfigurationProperties 就变得非必需。
但是如果为了更加稳妥可以把这两个注解全部都加上。
@Configuration和@Component都可以使其被spring容器管理。
@Slf4j
@Data
@ConfigurationProperties(prefix = "zzyl.framework.security")
@Configuration
public class SecurityConfigProperties {
}@Configuration
@EnableConfigurationProperties(SecurityConfigProperties.class)
public class SecurityConfig {@AutowiredSecurityConfigProperties securityConfigProperties;@AutowiredJwtAuthorizationManager jwtAuthorizationManager;
