谢岗网站建设,佛山外贸网站建设方案,国内优秀网站推荐,海口创建公司EnableConfigurationProperties ConfigurationProperties的使用时机 今天在写properties时想到了这个问题#xff0c;为什么有时候我需要写EnableConfigurationProperties有时候又不需要呢#xff1f;下面就详细讲讲。 Data
Component
ConfigurationProperties(pr…EnableConfigurationProperties ConfigurationProperties的使用时机 今天在写properties时想到了这个问题为什么有时候我需要写EnableConfigurationProperties有时候又不需要呢下面就详细讲讲。 Data
Component
ConfigurationProperties(prefix hm.auth)
public class AuthProperties {private ListString includePaths;private ListString 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;