要在不同的环境中执行不同的操作,您应该使用Spring Profiles。
假设您只需要在生产环境中加载安全配置bean,则应将其标记为仅在启用特定配置文件时有条件地加载。
@Configuration
@Profile("Production")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(details).passwordEncoder(new BCryptPasswordEncoder());
}
}
配置特定于配置文件的内容存储在名为application-{profile}.properties
和bootstrap-{profile}.properties
的属性文件中。
现在,由于安全配置bean标记为Production
,因此只有在启用Production
配置文件时才会加载它。
要启用配置文件,您必须设置以下属性。
spring.profiles.active=Production,Dev,Local
这个属性可以在常用的属性文件application.properties
中进行编辑(与针对特定配置文件,如application-Production.properties
条件加载不同的是,常用属性文件总是会被加载),或者可以按下面提供的方式作为环境变量提供。
On Windows
set SPRING_PROFILES_ACTIVE=Production
On Unix
export SPRING_PROFILES_ACTIVE=Production
可以使用Spring支持的其他许多方式来加载属性。要查看所有方法的列表,请转到此链接 https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
最后,要禁用默认的Spring安全(Basic)自动配置,您可以使用以下属性。
security.basic.enabled=false
management.security.enabled=false
在您希望禁用Spring Security自动配置的特定属性文件中,应按照上述格式进行设置。
security.basic.enabled=false
,这通常应该有效,但在使用WebSecurityConfigurerAdapter
时却无效。 - membersoundWebSecurityConfigurerAdapter
仍在创建一个bean,必须根据答案开头提到的条件进行加载。 - 11thdimension